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