Execute Script in Schedule using CronJob in Nodejs | Node Scheduler

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.

* * * * * /usr/local/bin/node /home/shahid/example/test.js

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.

npm install --save cron

Here is the basic syntax to use it.

var job = require('cron').CronJob;
 
new job('* * * * *', function(){
  console.log('running a task every minute');
});

Here is the Advance syntax to use.

var cronJob = require('cron').CronJob;
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.

job.isRunning();
// true

You can also stop the job anytime you want to.

if(job.isRunning()) {
 job.stop();
}

Hope this short tip helps you all!

Shahid
Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Articles: 126