MorningSleeper MorningSleeper - 1 month ago 17
Javascript Question

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()');
}

Answer

Probably not the most elegant approach, but since jobList lacks a length field, here is a way to achieve this:

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("Announcement0", rule, function() {
    // make my announcement
})

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

var jobList = schedule.scheduledJobs;

for (var i = 0; i < 2; i++) {
   eval('jobList.Announcement'+i+'.cancel()');
}

This removes the scheduled jobs from the list.

To check whether a job exists prior to deleting it:

for(var i = 0; i < 2; i++){
  var job = 'jobList.Announcement'+i;
  if(eval(job) != undefined) {
    eval(job+'.cancel()');
  }
}
Comments