Sling Academy
Home/Node.js/How to Schedule Tasks in Node.js

How to Schedule Tasks in Node.js

Last updated: December 30, 2023

Scheduling tasks in a Node.js application can be essential for performing operations at specified times or intervals. There are multiple ways to schedule tasks in Node.js, and this guide will cover three common solutions, including the built-in Timer functions, the ‘node-schedule’ package, and the ‘Agenda’ library.

Solution 1: Using Built-in Timer Functions

Node.js includes Timer functions such as setTimeout() and setInterval() natively in the global scope, which can be easily used to schedule tasks.

  • Set a one-time task with setTimeout().
  • Set a repeated task with setInterval().
const greeting = () => {
  console.log('Hello, World!');
};

// Schedule a one-time task after 3000ms
setTimeout(greeting, 3000);

// Schedule a repeating task every 5000ms
setInterval(greeting, 5000);

Pros: Built into Node.js, simple to implement, no additional packages required. Cons: Basic, not suited for complex scheduling, lacks persistence across application restarts.

Solution 2: Using ‘node-schedule’

‘node-schedule’ is a flexible cron-like and not-cron-like job scheduling library for Node.js.

  • Install the ‘node-schedule’ package.
  • Create a schedule and define job execution times using cron-style syntax.
// Step 1: Install node-schedule
// npm install node-schedule

const schedule = require('node-schedule');

// Step 2: Schedule a task using cron syntax
const job = schedule.scheduleJob('*/5 * * * * *', function(){
  console.log('Task is running every 5 seconds');
});

Pros: Advanced scheduling options, cron-style syntax, timezone support. Cons: Dependency on external library, complexity over in-built timers.

Solution 3: Using ‘Agenda’

‘Agenda’ is a more feature-rich job scheduling library for Node.js. Spread over different JS files.

Installation

// npm install agenda

Code example:

const Agenda = require('agenda');
const agenda = new Agenda({db: {address: 'mongodb://127.0.0.1/agenda'}});

agenda.define('say hello', job => {
  console.log('Hello!');
});

async function run() {
  await agenda.start();
  await agenda.every('1 minute', 'say hello');
}

run().catch(error => console.error(error));

Pros: Advanced scheduling features, persistence across restarts, job management with MongoDB storage. Cons: More complex setup, requires running MongoDB, dependency on external library.

Final Thoughts

Scheduling tasks in Node.js can range from straightforward Timer functions to using external libraries for more complex and feature-rich scenarios. Timer functions are best for simple cases where accuracy and persistence aren’t a priority. When complex timing patterns, persistence, and additional features are required, packages like ‘node-schedule’ allow for cron-style task scheduling while ‘Agenda’ provides comprehensive job scheduling backed by MongoDB. The choice among these solutions should be guided by the requirements of the application and the desired balance between simplicity and functionality.

Next Article: How to programmatically exit a Node.js program

Previous Article: Is it safe to delete the package-lock.json file?

Series: Node.js Intermediate Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates