node-schedule 全局内关闭定时器

摘要:用Cron表达式完成定时器,全局内关闭定时器需要获取到定时器的引用,scheduleJob存在第四个参数,然而readme中没有提及,可知API

Cron表达式

*    *    *    *    *    *
┬    ┬    ┬    ┬    ┬    ┬
│    │    │    │    │    │
│    │    │    │    │    └ day of week (0 - 7) (0 or 7 is Sun)
│    │    │    │    └───── month (1 - 12)
│    │    │    └────────── day of month (1 - 31)
│    │    └─────────────── hour (0 - 23)
│    └──────────────────── minute (0 - 59)
└───────────────────────── second (0 - 59, OPTIONAL)


用Cron表达式完成定时器

schedule.scheduleJob('0 1 * * *', () => {
 // something...
})


关闭定时器

API

let obj = schedule.scheduleJob('0 1 * * *', () => {
 // something...
})

obj.close();


全局内关闭定时器 -- 疑问

全局内关闭定时器需要获取到定时器的引用

看源码第607行

var name = (arguments.length >= 3 && typeof arguments[0] === 'string') ? arguments[0] : null;
  var spec = name ? arguments[1] : arguments[0];
  var method = name ? arguments[2] : arguments[1];
  var callback = name ? arguments[3] : arguments[2];

scheduleJob存在第四个参数,然而readme中没有提及,可知API

scheduleJob(name, spec, method, callback)
// name: 定时器的key值 spec: Cron表达式  method: method  callback: callback


全局内关闭定时器 -- 解决

首先定义定时器

scheduleJob(name, spec, method, callback)

在需要关闭的地方,写如下代码

function repeatSchedule(str) {
  for (var i in nodeschedule.scheduledJobs) {
    // 对比key值, key相同则重复
    if (nodeschedule.scheduledJobs[i].name.indexOf(str) > 0) {
      nodeschedule.scheduledJobs[i].close();
    }
  }
}


本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!

链接: https://shenqiku.cn/article/FLY_2852