6個占位符從左到右分別代表:秒、分、時、日、月、周幾
*表示通配符,匹配任意,當秒是*時,表示任意秒數都觸發,其它類推
// 每分鐘的第30秒觸發: '30 * * * * *' // 每小時的1分30秒觸發 :'30 1 * * * *' // 每天的凌晨1點1分30秒觸發 :'30 1 1 * * *' // 每月的1日1點1分30秒觸發 :'30 1 1 1 * *' // 2016年的1月1日1點1分30秒觸發 :'30 1 1 1 2016 *' // 每周1的1點1分30秒觸發 :'30 1 1 * * 1' // 每分鐘的1-10秒都會觸發,其它通配符依次類推 :'1-10 * * * * *'
調用定時器:
nodeTimer.scheduleTimer('30 * * * * *',function(err){ if(!err){ console.log('scheduleTimer:' + new Date()); } });
效果:
2、對象文本語法定時器
//每周一的下午15:03:30觸發,其它組合可以根據我代碼中的注釋參數名自由組合 nodeTimer.scheduleTimer({hour: 15, minute: 3, second: 30},function(err){ if(!err){ console.log('scheduleTimer:' + new Date()); } });
效果:
3、基于日期的定時器
var date = new Date(2019, 01, 07, 15, 03, 30); nodeTimer.scheduleTimer(date,function(err){ if(!err){ console.log('scheduleTimer:' + new Date()); } });
4、遞歸規則定時器
參數與對象文本語法定時器的參數類似
var rule = new schedule.RecurrenceRule(); rule.dayOfWeek = [0, new schedule.Range(4, 6)];//每周四,周五,周六執行 rule.hour = 15; rule.minute = 0; nodeTimer.scheduleTimer(rule,function(err){ if(!err){ console.log('scheduleTimer:' + new Date()); } });
5、取消定時器
// 取消定時器 // 調用 定時器對象的cancl()方法即可 nodeTimer.scheduleCancel = () => { // 定時器取消 cancelTimer.cancel(); console.log('定時器成功取消'); }
調用:
nodeTimer.scheduleCancel()
效果:
三,隊列
第一步:安裝async
npm install --save async
第二步:封裝方法
queue相當于一個加強版的parallel,主要是限制了worker數量,不再一次性全部執行。當worker數量不夠用時,新加入的任務將會排隊等候,直到有新的worker可用。
該函數有多個點可供回調,如worker用完時、無等候任務時、全部執行完時等。
const async = require('async'); /** *隊列 * @param obj :obj對象 包含執行時間 * @param callback :回調函數 */ const nodeQueue = async.queue(function (obj, callback) { setTimeout(function () { // 需要執行的代碼的回調函數 if(typeof callback==='function'){ callback(); } }, obj.time) }, 1) // worker數量將用完時,會調用saturated函數 nodeQueue.saturated = function() { console.log('all workers to be used'); } // 當最后一個任務交給worker執行時,會調用empty函數 nodeQueue.empty = function() { console.log('no more tasks wating'); } // 當所有任務都執行完時,會調用drain函數 nodeQueue.drain = function() { console.log('all tasks have been processed'); } module.exports = nodeQueue;
第三步:調用方法
const nodeQueue = require('./node_queue.js'); for (let i = 0; i < 10; i++) { nodeQueue.push({ name: 1, time: 2000 }, function (err) { console.log('隊列執行錯誤信息==',err); if(!err){ // 需要執行的代碼或函數 console.log('需要執行的代碼或函數第',i+1,'個') } }) };
效果:
總結
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com