Cron Job Functionality In Nodejs

Posted By : Vivek Joshi | 03-Jul-2017

For scheduling time specific jobs in nodejs we can use node-cron module using following steps

 

step 1:- first we install node-cron module from npm

npm install --save node-cron

step 2:- create a function for scheduleling cron jobs

Step 3:- create function and schedule crone jobs

function scheduleJosbs(){
 var cron = require('node-cron');
 cron.schedule('* * * * *', function(){
 console.log('running a task every minute'); 
});
}

in cron's schedule function '*' are define different time period these are follow and make sure do define the * as same format separate with space.

* * * * * *
from left to right
* second (optional)
* minute
* hour
* day of month
* month
* day of week
 

 

field value
second 0-59
minute 0-59
hour 0-23
day of month 1-31
month 1-12 (or names)
day of week 0-7 (or names, 0 or 7 are sunday)

these are the some example for scheduling jobs for different time periods

function scheduleJosbs(){
 var cron = require('node-cron');
//in schedule function first * is optional it is use for defining seconds if you are not working on seconds jobs 
//so you can define only five '5' starts which is start from minutes
cron.schedule('* * * * * *', function(){
 console.log('running a task every second'); });
 cron.schedule('1,2,4,5 * * * *', function(){
 console.log('running every minute 1, 2, 4 and 5');
 });
 cron.schedule('1-5 * * * *', function(){ 
console.log('running every minute to 1 from 5'); 
}); 
cron.schedule('*/2 * * * *', function(){
 console.log('running a task every two minutes');
 });
 cron.schedule('* */2 * * *', function(){ 
//this job will run in every two hours in this hour it will run every minutes (e.g 2:1,2:2 ) because we have define minutes as *; 
//if you want to run this job only once in two hours so you have to define minutes also (e.g '0 */2 * * *' run once in every two hours
 console.log('running a task every two hours'); 
}); 
cron.schedule('* * * January,September Sunday', function(){
 //you can define sort name of months and days(e.g ('* * * jan,sep sun') 
//and number of months and days
console.log('running on Sundays of January and September');
});
}

About Author

Author Image
Vivek Joshi

Vivek is Web App Developer in Java Technology and also working on NodeJS.

Request for Proposal

Name is required

Comment is required

Sending message..