7

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.

Rohan
  • 71
  • 1
  • 1
  • 2

4 Answers4

16

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

Aritra Chakraborty
  • 12,123
  • 3
  • 26
  • 35
  • 1
    For node-cron the solution from @amoghesturi works. Also it has a `cron.getTasks()` method and each task has a `.start` and `.stop` method. – Aritra Chakraborty Oct 09 '19 at 08:57
  • I currently ran into a similar issue with job-instantiation (IOT publishing via mqtt) and termination. Thanks for the info - maybe we could expand your answer to cover cron, node-cron & node shedule - would be a nice reference for the future - what do you think? – iLuvLogix Oct 09 '19 at 09:25
  • 1
    You are most welcome to edit the answer. I will be sure to approve it. :-) – Aritra Chakraborty Oct 09 '19 at 11:35
  • ok, give me an hour or so and I'll write a comprehensive summary ;) – iLuvLogix Oct 09 '19 at 11:42
  • 1
    np - reputation are just points to me anyway - I put our credits on the bottom ;) Please check the summary for any errors or typos and edit if you find any ;) – iLuvLogix Oct 09 '19 at 12:20
  • 3
    some of the method signatures do not seem to be correct. require('cron').CronJob does not have the method "scheduleJob" and nor does require('node-cron') – Alex Busuioc Mar 27 '20 at 17:28
  • Yes, the schedulejobs were basically pseudocodes. The main point was to show how to stop them, but now the syntaxes and constructors are different as heck. so it is not relevant that much. – Aritra Chakraborty Oct 14 '20 at 12:46
  • How to stop a job if node server restarts and the schedule is saved in db, but the job instances list is gone after server restart? – Shiv Apr 13 '22 at 11:40
1
var cron = require('node-cron');

  var task = cron.schedule('* * * * *', () =>  {
    console.log('will execute every minute until stopped');
});
task.stop(); 
amoghesturi
  • 238
  • 3
  • 13
  • 1
    Actually there are many jobs which are running in my program . This function (runScheduler) is being called for different urls. I just want to stop the job for a particular url. – Rohan Dec 08 '18 at 17:14
0

I successfully used cron-job-manager to create, read, update, delete jobs.

After you add a job manager.add('key','* 30 * * * *', taskFunction) you can easily stop it manager.stop('key') or delete it manager.deleteJob('key')

Alex Busuioc
  • 992
  • 1
  • 11
  • 24
0

I faced the same Issue. Using node-schedule solved the issue with a custom ID per Job:

start the custom Job:

  const campaignId = "MY_CUSTOM_ID"
  let job = schedule.scheduleJob(campaignId, '* * * * * *', function () {
    console.log('running campaign: ' + campaignId)
  })

stop the custom Job:

  const campaignId = "MY_CUSTOM_ID"
  let current_job = schedule.scheduledJobs[campaignId]
  current_job.cancel()
Alan
  • 9,167
  • 4
  • 52
  • 70