Schedule Jobs in NodeJS

Posted By : Vipul Pandey | 26-Sep-2016

In this blog I am going to explain writing the scheduled Jobs which will perform certain
action based on our requirement on a particular time / day instance.

For performing the above task we are going to use CRON package of node.

To add a job we need to
1) Install Cron 

          npm install cron      

2) Require cron 's CronJob to our project.

          var CronJob = require('cron').CronJob

3) Create an instance of CronJob

         var jobs = new CronJob({
            cronTime: ' * * * * * *',
              onTick: function () {
                   //perform Your action
              },
              start: false,
              timeZone: 'Asia/Kolkata'
            });
 

Arguments
cronTime: it takes 6 arguments as
  1) Second - > 0 - 59
  2) Minute - > 0 - 59
  3) Hour - > 0 - 23
  4) Day of Month - > 1 - 31
  5) Months - > 0 - 11
  6) Day of Week - > 0 - 6
 

Note:We Can define cronTime in ranges alse like * for always.
0 - 59 / 5 at every 5 minute.

onTick: The operation to perform.
Start: It takes a boolean and if true then starts the job now.
timeZone: jobs 's timeZone 

4) To start Job

 

                 jobs.start()
      

 

Example:

var jobs = new CronJob({
        cronTime: ' 00 00 0-23 * * *',
        onTick: function () {
            printMyName();
        },
        start: false,
        timeZone: 'Asia/Kolkata'
    });

   jobs.start();

 var printMyName = function () {
     var date = new Date(); 
    console.log("Hi Vipul  it is ", today);
 };
        

THANKS

About Author

Author Image
Vipul Pandey

Vipul Pandey is a good team-player & developing application on MEAN and java spring boot. Vipul loves to keep rotating fingers in his keyboard until he creates somethings inspiring.Hobbies are playing cricket ,swimming & photography.

Request for Proposal

Name is required

Comment is required

Sending message..