How to Schedule Tasks in Node.js

OpenJavaScript 0

Last updated: December 10, 2022.

Using the node-schedule library, you can schedule tasks to occur at a specific time point or repeatedly.

Typically, this is useful for scheduling web scraping and recurring HTTP requests and/or database operations.

Installing node-schedule

First, if unsure, make sure you have followed the steps to install Node on your system.

Then, inside your project folder, create a new Node project and install node-schedule by running npm i node-schedule:

cd C:\Users\You\Desktop\Node-Project
npm init --y
npm i node-schedule

Finally, inside your project folder, you can import the package under the reference schedule using require():


// App.js
const schedule = require("node-schedule");

Scheduling Tasks

For a specific time point

node-schedule works with the native JavaScript Date object. So first, create one containing the date when you want the task to occur.

Then call scheduleJob on the library, passing in the newly created Date object as a first argument and the task you want to run inside a function inserted as the second argument:

const date = new Date(2023, 11, 9, 10, 00, 00);

schedule.scheduleJob(date, () => {
    console.log("Completed job @ " + date.toString());
});

The above task will execute on December 9, 2023 at 10:00 AM.

Repeating task

To schedule a repeat task, pass in a cron expression as a string in the first argument position.

The expression below repeats the task every 2 seconds:

schedule.scheduleJob('*/2 * * * * *', () => {
    console.log("Done job @ " + new Date().toString());
});

If you are unfamiliar with cron expressions, this free cron expression generator will help you learn to write your own.

Cancelling a task

To cancel a task, you need to save a reference to the task you want to cancel. This is available as a return value when you first schedule a new task.

Then, simply call the cancel() method on the task:

const job = schedule.scheduleJob('*/2 * * * * *', () => {
    console.log("Done job @ " + new Date().toString());
    job.cancel();
});

Related links