在項目中有個每天0點執行的函數,本來想用setInterval來實現,但覺得這種需求以后應該還會有,自己寫可能拓展性不高。
搜了一下發現了node-schedule這個包。
現在記錄一下使用方法
node-schedule沒次都是通過新建一個scheduleJob對象來執行具體方法。
時間數值按下表表示
* * * * * *┬ ┬ ┬ ┬ ┬ ┬│ │ │ │ │ |│ │ │ │ │ └ [dayOfWeek]day of week (0 - 7) (0 or 7 is Sun)│ │ │ │ └───── [month]month (1 - 12)│ │ │ └────────── [date]day of month (1 - 31)│ │ └─────────────── [hour]hour (0 - 23)│ └──────────────────── [minute]minute (0 - 59)└───────────────────────── [second]second (0 - 59, OPTIONAL)
使用node-schedule在指定時間執行方法
var schedule = require('node-schedule');var date = new Date(2017, 11, 16, 16, 43, 0);var j = schedule.scheduleJob(date, function(){ console.log('現在時間:',new Date());});
在2017年12月16日16點43分0秒,打印當時時間
指定時間間隔執行方法
var rule = new schedule.RecurrenceRule();rule.second = 10;var j = schedule.scheduleJob(rule, function(){ console.log('現在時間:',new Date());});
這是每當秒數為10時打印時間。如果想每隔10秒執行,設置 rule.second =[0,10,20,30,40,50]即可。
rule支持設置的值有second,minute,hour,date,dayOfWeek,month,year
同理:
每秒執行就是rule.second =[0,1,2,3......59]
每分鐘0秒執行就是rule.second =0
每小時30分執行就是rule.minute =30;rule.second =0;
每天0點執行就是rule.hour =0;rule.minute =0;rule.second =0;
....
每月1號的10點就是rule.date =1;rule.hour =10;rule.minute =0;rule.second =0;
每周1,3,5的0點和12點就是rule.dayOfWeek =[1,3,5];rule.hour =[0,12];rule.minute =0;rule.second =0;
....
示例
1:確定時間
例如:2014年2月14日,15:40執行
var schedule = require("node-schedule"); var date = new Date(2014,2,14,15,40,0); var j = schedule.scheduleJob(date, function(){ console.log("執行任務"); });
取消任務
j.cancel();
2:每小時的固定時間
例如:每小時的40分鐘執行
var rule = new schedule.RecurrenceRule(); rule.minute = 40; var j = schedule.scheduleJob(rule, function(){ console.log("執行任務"); });
3:一個星期中的某些天的某個時刻執行,
例如:周一到周日的20點執行
var rule = new schedule.RecurrenceRule(); rule.dayOfWeek = [0, new schedule.Range(1, 6)]; rule.hour = 20; rule.minute = 0; var j = schedule.scheduleJob(rule, function(){ console.log("執行任務"); });
4:每秒執行
var rule = new schedule.RecurrenceRule(); var times = []; for(var i=1; i<60; i++){ times.push(i); } rule.second = times; var c=0; var j = schedule.scheduleJob(rule, function(){ c++; console.log(c); });
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答