We use crontab utility of Linux to run some job in an interval of minutes, hours, days or week. Crontab is widely used and I am sure most of you have either used or heard of it.
Generally, this is how we use Crontab to execute Node.js code.
Suppose your code is placed in test.js and you want to execute it every minute. You will make the entry in Crontab, something like this.
This shall run every minute and execute your Node.js code, however, is this a reliable and efficient way?
Well, I think no.
There is a node module for cron built on top of setTimeOut() which you can use in your program.
Install the node module.
Here is the basic syntax to use it.
new job('* * * * *', function(){
console.log('running a task every minute');
});
Here is the Advance syntax to use.
var job = new cronJob({
cronTime: '* * * * * *',
onTick: function() {
// call some function.
// create child process
// Do whatever you want to do!
},
start: false,
timeZone: 'Asia/Kolkata'
});
job.start();
You can also if the job is running or not.
// true
You can also stop the job anytime you want to.
job.stop();
}
Hope this short tip helps you all!