Cron jobs are important when some script is required to be executed at a fixed time over and over again. It does not require an user to be present to execute the script.
Cron jobs in Node.js can be setup using an external module known as node-cron. This module is based on GNU crontab. This tutorial will show how to use the module.
Installing node-cron
To install the module the following command is executed from the terminal :
npm install node-cron --save
To use node-cron the module has to be imported :
const cron = require('node-cron');
Setting up a Cron Job
The schedule method is used to setup a cron job. This accepts 3 parameters :
- Interval or the time at which the cron job is needed to run
- The callback function which contains the code to be executed
- The third parameter is optional and passed as an object. The third parameter accepts 2 fields in an object form :
- scheduled : accepts a boolean value. If set to false then the cron won't start automatically
- timezone : accepts the timezone and will interpret the time set in the first parameter of schedule method accordingly
As an example, this snippet will print the line in the terminal every minute :
const cron = require('node-cron');
var task = cron.schedule('* * * * *', () => {
console.log('Printing this line every minute in the terminal');
});
The below snippet will print the line in the terminal every day when the time at "Europe/London" timezone is 17:50 Hours :
const cron = require('node-cron');
// cron wont start automatically
var task = cron.schedule('50 17 * * *', () => {
console.log('Printing this line every day at 1750 Hours London Time.');
}, {
scheduled: false,
timezone: "Europe/London"
});
// start method is called to start the above defined cron job
task.start();
Setting the Time in a Cron Job
In setting up a cron job, the most important aspect is to set up the time or the interval at which the supposed code will be executed. This is done by defining a time field.
The time field has six fields, as shown below :
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | second (optional) (Valid range 0-59)
| | | | | | | | | | | | | | | | | | | | | | | | | | | minute (Valid range: 0-59)
| | | | | | | | | | | | | | | | | | | | | | | | | hour (valid range: 0-23)
| | | | | | | | | | | | | | | | | | | | | | | day of the month (Valid range: 1-31)
| | | | | | | | | | | | | | | | | | | | | month (Valid range: 1-12 or names of the months)
| | | | | | | | | | | | | | | | | | day of the week (valid range: 0-7 or names of the days: both 0 and 7 denotes Sunday)
| | | | | |
| | | | | |
* * * * * *
Permissible values for each field is shown above within brackets. An asterisk implies the expression of time for that field matches all values of the field.
Below are few examples on setting up the time of a cron job.
-
If a cron job needs to be executed every second :
cron.schedule('* * * * * *', () => { // code });
-
If a cron job needs to be executed at the start of every minute, the time can be set in 2 ways as shown :
cron.schedule('0 * * * * *', () => { // code });
// Note there are 5 asterisks cron.schedule('* * * * *', () => { // code });
-
Similarly to run a cron job every hour, setting the minute field to 0 will run the cron job at the start of an hour. If the minute field is set to some other valid value, the cron job will run at the defined minute every hour.
cron.schedule('0 * * * *', () => { // code });
-
If a cron job has to run on th 15th of every month at 01:00 Hours, the time is set in the following manner :
cron.schedule('* 01 15 * *', () => { // code });
-
The time in cron job can also be in a range of values :
// schedules the task to be executed every minute between 5th and 15th minute each hour cron.schedule('5-15 * * * *', () => { // code });
-
Multiple values can also be passed to the cron job, the values are comma separated :
// task will be executed at 45th and 50th minute of each hour cron.schedule('45,50 * * * *', () => { // code });
-
To run the cron job every two minutes :
cron.schedule('*/2 * * * *', () => { // code });
If in the above snippet, if the */2 is replaced with */3 the cron job will run every 3 minutes (known as stepping). Stepping can also be used in conjunction with ranges.
Starting a Cron job
If the scheduled key in the third parameter of schedule method has been set to false, the cron won't start automatically. In such cases or in case the cron job has been stopped, the cron is started by calling the start method.
const cron = require('node-cron');
// cron wont start automatically
var task = cron.schedule('* * * * *', () => {
console.log('This line will be printed only when the start method is called');
}, {
scheduled: false
});
// starts the cron job
task.start();
Stopping or Pausing an Ongoing Cron Job
If the need arises to stop or pause an ongoing cron job, it is achieved by calling the stop method. The cron job can again be restarted by calling the start method.
const cron = require('node-cron');
var task = cron.schedule('* * * * *', () => {
// code
});
// stops the cron job
task.stop();
Destroying a Cron Job
If a cron job has to be destroyed, the destroy method is called. This method stops and destroys a cron job. Even if the start method is called afterwards, the cron wont start unlike in stop method.
const cron = require('node-cron');
var task = cron.schedule('* * * * *', () => {
//Some cron job is running
});
// stops and destroys the cron job
task.destroy();
// wont start the cron job as it has been destroyed
task.start();
Other Details
Most of the things in the node-cron module have been covered here. However you can see the detailed documentation here.