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'

You can also if the job is running or not.

// true

You can also stop the job anytime you want to.

if(job.isRunning()) {

Hope this short tip helps you all!

3 thoughts on “Execute Script in Schedule using CronJob in Nodejs | Node Scheduler”

  1. Shahid, thanks for this article
    If I create a http://www.mysite.com/test/testcron.js file and inside it make a cronjob and at the end of the file write job.start()… then how should I run it? I mean how should we say to our server to start running this file?
    I’m a newbie in node.js would you plz explain me a little
    best regards

Comments are closed.