Cron tasks

How to create cron workers using Node.js.

Install the cron module:

1
$ npm install cron

Take a look at this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Require the cron module 
const CronJob = require('cron').CronJob;

// Declare variables to set up the cron job
const frequency = '* * * * * *',
startNow = false,
timeZone = 'Europe/Madrid';

// Simple counter variable to show the example
let counter = 0;

// If counter is 5, stops the job. Else increments 1 the counter variable.
const taskToDo = () => {
console.log('Task is runnning and counter is ' + counter);
}

// It is executed only when job is done
const endTask = () => {
console.log('Task is done');
}

// Declare and initialize the cron job
const myJob = new CronJob(frequency, taskToDo, endTask, startNow, timeZone);

// Start the cron job
myJob.start();
  • '* * * * * *' is saying to cron to execute every second.
  • startNow = false is saying to cron to wait until myJob.start() is called.
  • taskToDo is the function to be executed every second.
  • endTask is the function to be executed once time the cron finish(myJob.stop())
  • This simple script is executing a function every second. That function increments by one a counter.

If you execute the above example you should see something like this:

$ node test.js 
    Task is runnning and counter is 0
    Task is runnning and counter is 1
    Task is runnning and counter is 2
    Task is runnning and counter is 3
    Task is runnning and counter is 4
    Task is runnning and counter is 5
    ...

References