如何删除节点计划中的所有计划?

时间:2016-10-07 20:57:50

标签: javascript node.js scheduled-tasks

我从docs看到您可以逐个名称删除,例如......

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

但是我想要代码来获取所有预定作业,然后循环遍历它们以删除每个作业。我认为以下所有工作......

var jobList = schedule.scheduledJobs;

输出控制台......

{ '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] } }

如何循环使用jobList来删除每个作业?

替代代码:

var jobList = schedule.scheduledJobs;

for(jobName in jobList){
  var job = 'jobList.' + jobName;
  eval(job+'.cancel()');
}

4 个答案:

答案 0 :(得分:4)

最好远离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);

答案 1 :(得分:2)

可能不是最优雅的方法,但由于jobList缺少长度字段,因此这是实现此目的的一种方法:

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

这将从列表中删除预定作业。

要在删除作业之前检查作业是否存在:

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

当然,您也可以使用for-in。请记住,如果您使用for-in结果在常规for循环中排序时没有排序,那么您可能会遇到一些意外行为:

var jobList = schedule.scheduledJobs;

for(jobName in jobList){
  var job = 'jobList.' + jobName;
  eval(job+'.cancel()');
}

答案 2 :(得分:2)

一行:

for (const job in schedule.scheduledJobs) schedule.cancelJob(job);

答案 3 :(得分:0)

var jobList = cron.scheduledJobs; //Get All scheduled jobs

Object.values(jobList).map(job => {
  console.log("Each Job", job.name);

    cron.cancelJob(job.name);
  })