Scheduling Tasks using Cron-Jobs in Node.js

Have you ever wanted to run your code on a specific time without your intervention? Maybe you wanted to generate a scheduled report or send emails on a specific time interval or maybe you wanted to automate a process you do every day at a specific time interval. Now, There ways you could achieve that one way could be asking someone else to run it for you. A different way would be to schedule a cronjob to run on a specific interval.

CRON in itself is a command on Unix-like operating system to create jobs or process which are executed at a specified time. Now, In Node we would be using node-cron package to make cron jobs.

Create a node project and Install Node-Cron using the below command.

npm init -y & npm i node-cron

Basic Node-Cron scheduled Program

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

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

If you run the above program it would print the message every second. As it is scheduled to run every second. Those asterisks represent the time value that this program is scheduled to run.

Let’s understand Cron Scheduling with a very simple example

Understanding CRON Expressions

As you can see we have 6 *(asterisks) that represent a certain portion of time. The first asterisks represents the second value and is in range [0-59] because that many we have in a minute. if you leave the value to be asterisks it would run every second . In fact the entire value out there means .Run this code Every second of Every minute of Every hour of Every day of Every month of Every Day of the week.

Remembering the above line in bold is very important as if you change any value to their numerical or text(We will see this later) Doesn’t mean it will run at that time interval. for example, if you use scheduling of say `5 * * * * *`. It does not mean run every 5 seconds but it rather means run this code on the 5th second of Every Minute of Every hour of Every day of Every month of Every day of the week.

Lets discuss the possible values for these astericks. If you try to use any other value outside the list of the possible allowed value. The node-cron package will throw you an error.

  • The first asterisks that represent seconds can have a value between 0-59. This asterisk is also optional.
  • The second asterisks that represent minute can have a value between 0-59.
  • The third asterisks that represent the hour can have values between 0-23.
  • The fourth asterisks that represent the day of the month can have a value between 0-31.
  • The fifth asterisks that represent the month can have either value between 1- 12 or the name of the month.
  • The sixth asterisks that represent the day of the week can have a value between 0-7(both o and 7 represent Sunday) or names of the day.

In Case you are not sure whether your cron-expression is valid or not node-cron provides us with a method called validate which would return boolean values.The boolean values represent whether the cron expression is valid or not.

var isValid = cron.validate('* * * * *');

If the above function represents true than it means the expression is valid for scheduling.

Using Schedulers in different ways

Using Multiple values

cron.schedule('1,2,3,4,5,6,7,8,9,10 * * * * *', () => {
    console.log('running a cron job first 10 seconds of a minute');
});

The Node-Cron package allows you to use multiple values that are separated by commas to schedule a job. Now, remember the statement we discussed above. This would then say it would run every first, second, third, fourth…..tenth second of every minute of every hour of every day of the month every of month of every day of the week. In short, it means to run this code every first 10 seconds of a minute and this is exactly what it does.

You can do the above task by using ranges as well.

cron.schedule('1-10 * * * * *', () => {
    console.log(' running a cron job every second');
});

Now both the start and end value our inclusive it runs similarly to our scheduler defined above this. Now Node-Cron also gives you an option to define a constant gap to run your job say if you wanted to run a process between 1 to 30 seconds of every minute with a gap of say 3 sec you could use a range that specifies 1 to 30 seconds followed by ‘/’ and a number that specifies the gap between each successive run

cron.schedule('1-30/3 * * * * *', () => {
    console.log(' running a cron job every second');
});

The above code would run our process on the first 30 seconds of a minute with a gap of 3 seconds between each run. Now you can also use step with * that would mean to run a process every __(whatever place you are using at) with a gap of the number specified after ‘/’.

Scheduling Jobs with Name of days and Month.

cron.schedule('* * * * June Thursday,Friday', () => {
    console.log((++i)+' running a cron job every second');
});

Now, while I am writing this part it is 23:58 on the 4th of June which is Thursday. This schedule would make my code run every second of every hour of every minute of every day of the month of June on Thursday and Friday. Now, this would run every second for me till Friday ends which is due to start in around a minute.

You can also pass and additional options object to the schedule function that is

cron.schedule('* * * * June Thursday,Friday', () => {
    console.log((++i)+' running a cron job every second');
},{
    timezone:'Asia/Kolkata',
    scheduled:false
});

So we pass an optional object with parameter timezone that refers to the timezone we would be using. You can find the entire list of the accepted timezone here and a boolean value scheduled whose default value is true. If you set it to false you will have to manually start the job using the .start() .

Now we know how to create a scheduler but you may want to start or end a scheduler based on some event. In this case you may want to use the .start() and .stop() methods.

Using the start() function to start a cron job

var cron = require('node-cron');
var i=0;
var task = cron.schedule('* * * * June Thursday,Friday', () => {
    console.log((++i)+' running a cron job every second');
},{
    timezone:'Asia/Kolkata',
    scheduled:false
});


task.start();

Similarly you could stop the function there is also a destroy function the main difference between a stop and a destroy is that a stopped job could be resumed but the destroyed job can not be.

There was it How to scheduled cron jobs in Node.js. You can use the knowledge here to multiple places like scheduling emails to be sent, to getting scheduled reports of event occurring in your website all you have to do is to write the function to do the same and wrap it in the cron scheduler that would automate the process for you.

Leave a Reply