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,'个') } }) };
效果:
总结