Cron Job in Nodejs

Cron Job in Nodejs

In this blog, we will learn how to create a cron job in nodejs. For this, we will be using node package node-cron. Source code of this package can be found on Github using this link.

So lets get started with it. First install node-cron as under

npm install --save node-cron

Then, in the code, import this package as

var cron = require("node-cron");

and then you can schedule cron jobs as

cron.schedule("* * * * * *", () => {
    console.log("running a task every second");
  });

In the above example, we create a cron job and parameter passed to schedule function are * * * * * * . Explanation of this is as

Values allowed

fieldvalue
second0-59
minute0-59
hour0-23
day of month1-31
month1-12 (or names)
day of week0-7 (or names, 0 or 7 are sunday)

Operators than can be used

OperatorUsage
/for step values
,value list separator
range of values

These operators have been explained in the Examples section.

Examples of Cron Job in NodeJS

Run cron job every day at 10:30:20 AM

cron.schedule("20 30 10 * * *", () => {
    console.log("running a task everyday at 10:30am");
  });

Run cron job on the first of every month

cron.schedule("0 0 1 * *", () => {
    console.log("running a task on the 1st of every month at 00:00");
  });

Run cron job every hour

cron.schedule("0 * * * *", () => {
    console.log("running a task hourly");
  });

There is another way for doing so.

‘/’ operator helps you to get step values as illustrated in the table earlier. It can be used in the following way. If you want a cron job to run every hour, you can write */1 in the place holder for an hour. Similarly, you can write */5 in the place holder for an hour if you want the cron job to run every 5 hours. Example of running cron job every hour is here:

cron.schedule(" 0 */1 * * *", () => {
    console.log("running a task hour");
  });

Run cron job after every 10 mins

cron.schedule(" */10 * * * *", () => {
    console.log("running a task hour");
  });

Run cron job on a particular date

cron.schedule(" 0 0 1 11 *", () => {
    console.log("runs the task on 1st November at 00:00 hrs every year");
  });

Run cron job using multiple values

Lets say you want to run a cron job on 1,2,4 and 5 minute:

cron.schedule('1,2,4,5 * * * *', () => {
  console.log('running every minute 1, 2, 4 and 5');
});

Run cron job using a range

If you want a cron job to run from every minute 1-5.

cron.schedule('1-5 * * * *', () => {
  console.log('running every minute to 1 from 5');
});

Run cron using name

For month and week day you also may use names or short names.  e.g

cron.schedule('* * * January,September Sunday', () => {
  console.log('running on Sundays of January and September');
});

or we can also use short names

cron.schedule('* * * Jan,Sep Sun', () => {
  console.log('running on Sundays of January and September');
})

Happy Scheduling!

Share This Post