How to stop a node cron job

Rohan picture Rohan · Dec 8, 2018 · Viewed 13.2k times · Source

I want to stop a node cron job on certain conditions.

This is how I started the task to run every 1 second.

const runScheduler = (url)=>{
    cron.schedule('*/1 * * * * *', () => {
        console.log('running a task every one second');
        async.waterfall([ getUrlDelay(url), dbMethods.updateUrlResponses(url) ],function(err, success){
            if(err) return console.log('Url Not Found');
        })
      });
}

I want to stop this job but unable to do it.

Answer

Aritra Chakraborty picture Aritra Chakraborty · Dec 8, 2018

The below answer may not be relevant now because of the changes done to these packages. The scheduleJob was meant to be a pseudocode to just create a job. The objective was to show how to stop them.


Here's a comprehensive summary for instantiating, starting and stopping sheduled cron-jobs for three cron-modules (cron, node-cron & node-schedule):

1. CRON

In order to cancel the job you can create a job with unique name.

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

var j = cron.scheduleJob(unique_name, '*/1 * * * * *',()=>{
    //Do some work
});
// for some condition in some code
let my_job = cron.scheduledJobs[unique_name];
my_job.stop();

It should cancel the job.

2. NODE-CRON

var cron = require('node-cron');

const url_taskMap = {};
const task = cron.schedule('*/1 * * * * *',()=>{
    //Foo the bar..
});
url_taskMap[url] = task;
// for some condition in some code
let my_job = url_taskMap[url];
my_job.stop();

3. NODE-SCHEDULE

var schedule = require('node-schedule');

let uniqueJobName = specificURL;
// Shedule job according to timed according to cron expression
var job = schedule.scheduleJob(uniqueJobName,'*/10 * * * * *', function(){
     //Bar the foo..
});
// Inspect the job object (i.E.: job.name etc.)
console.log(`************** JOB: ******************`);
console.log(job);

// To cancel the job on a certain condition (uniqueJobName must be known) 
if (<someCondition>) {
    let current_job = schedule.scheduledJobs[uniqueJobName];
    current_job.cancel();
}

Summarized by Aritra Chakraborty & ILuvLogix