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.
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');
});
}
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Vivek Joshi
Vivek is Web App Developer in Java Technology and also working on NodeJS.