irom
irom

Reputation: 3606

nodejs cron to schedule 3 jobs

I have the following code to schedule 3 jobs in 5 sec:

var moment = require('moment');
var CronJob = require('cron').CronJob;
for (i=0; i < 2; i++)
var job = new CronJob(moment().add(1, 'minutes').toDate(), function(){
    console.log(i);
}, true, 'America/Los_Angeles');

but instead of printing 0,1,2 it prints only 3 three times. So run the last job 3 times ? $node test-cron.js 3 3 3

Upvotes: 1

Views: 3533

Answers (1)

Adam Wysocki
Adam Wysocki

Reputation: 323

Watch the scope of the 'i' in your for loop. In your original code, by the time the jobs run the value of the global 'i' has changed. (Although I'm not sure why it's printing '3' when the for loop is '< 2'). The sample code below creates three cron jobs and runs them every 5 seconds.

var CronJob = require('cron').CronJob;

function scheduleJob(counter) {
    var job = new CronJob('*/5 * * * * *', function(){
            console.log(counter);
    }, true, 'America/Los_Angeles');

    return job;    
}

for (i=0; i < 3; i++) {
    scheduleJob(i);
}

Upvotes: 2

Related Questions