Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete all schedules in node-schedule?

I see from docs you can delete one by one by name for example ...

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

 // sample announcement

 var rule = new schedule.RecurrenceRule();
 rule.dayOfWeek = [1, 2, 3, 4, 5];
 rule.minute = 50;
 rule.hour = 12;

 var message = schedule.scheduleJob("AnnouncementOne", rule, function() {
    // make my announcement
})

AnnouncementOne.cancel();

but I would like code to get all scheduled jobs and then loop through them to delete each one. I think the following gets all the jobs ...

var jobList = schedule.scheduledJobs;

which outputs following to console ...

{ 'AnnouncementOne':
   Job {
     job: [Function],
     callback: false,
     name: 'AnnouncementOne',
     trackInvocation: [Function],
     stopTrackingInvocation: [Function],
     triggeredJobs: [Function],
     setTriggeredJobs: [Function],
     cancel: [Function],
     cancelNext: [Function],
     reschedule: [Function],
     nextInvocation: [Function],
     pendingInvocations: [Function] },
  'AnnouncementTwo':
   Job {
     job: [Function],
     callback: false,
     name: 'AnnouncementTwo',
     trackInvocation: [Function],
     stopTrackingInvocation: [Function],
     triggeredJobs: [Function],
     setTriggeredJobs: [Function],
     cancel: [Function],
     cancelNext: [Function],
     reschedule: [Function],
     nextInvocation: [Function],
     pendingInvocations: [Function] } }

how do I loop through jobList to delete each job?

Alternative Code:

var jobList = schedule.scheduledJobs;

for(jobName in jobList){
  var job = 'jobList.' + jobName;
  eval(job+'.cancel()');
}
like image 882
MorningSleeper Avatar asked Nov 21 '25 09:11

MorningSleeper


1 Answers

It is better to keep away from eval

const schedule = require('node-schedule');
const _ = require('lodash');
const j = schedule.scheduleJob('SomeDirtyWork', '42 * * * *', () => {
  // Something is going on
});

const jobNames = _.keys(schedule.scheduledJobs);
for(let name of jobNames) schedule.cancelJob(name);
like image 189
Johan Willfred Avatar answered Nov 22 '25 21:11

Johan Willfred