NodeJs入门教程之定时器和队列(2)

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

效果:

NodeJs入门教程之定时器和队列

三,队列

第一步:安装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,'个') } }) };

效果:

NodeJs入门教程之定时器和队列

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/68b0f9cf7b5a90bec5812d407b7fbf13.html