Search code examples
javascriptnode.jscron

onComplete() does not get called in node cron


Hi i am trying to test out node-cron but i am not able to get desired response in one case.

I need to initiate cron request one more time when current cron gets completed. So, i need onComplete() to get called but i am not able to get the callback.

My code snippet is :

CronWrapper.prototype.pushNotificationCron = function() {
    // change console to winston in real implementation.
    console.log('Creating job');
    var jobPattern = '*/10 * * * * *';
    var job = new CronJob(jobPattern, onJobStarted, onJobCompleted, false);
    console.log('Starting job');
    job.start();
};

var onJobStarted = function(){
    var date = new Date();
    console.log('Cron started on \t' + date);
    return;
};

var onJobCompleted = function(){
    winston.info('Job completed:');
};

Output:

Cron started on     Tue Dec 16 2014 12:59:40 GMT+0530 (IST)
Cron started on     Tue Dec 16 2014 12:59:50 GMT+0530 (IST)
Cron started on     Tue Dec 16 2014 13:00:00 GMT+0530 (IST)

Please point out what mistake i am making.

Lib details:

"cron":"1.0.5"


Solution

  • After reading documentation more closely, i found i was missing calling stop().

    As stated on documentation

    onComplete - [OPTIONAL] - A function that will fire when the job is complete, when it is stopped.

    So now i am manually calling the stop() on completion and getting the callback. So now my code looks like:

    CronWrapper.prototype.pushNotificationCron = function() {
        // change console to winston in real implementation.
        console.log('Creating job');
        var jobPattern = '*/10 * * * * *';
        var job = new CronJob(jobPattern, function(){
            var date = new Date();
            console.log('Cron started on \t' + date);
            job.stop();
        }, onJobCompleted, false);
        console.log('Starting job');
        job.start();
    };
    
    // var onJobStarted = function(){
    //  var date = new Date();
    //  console.log('Cron started on \t' + date);
    
    // };
    
    var onJobCompleted = function(){
        winston.info('Job completed:');
    };
    

    Output

    Cron started on     Tue Dec 16 2014 13:13:30 GMT+0530 (IST)
    info: Job completed: