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

2020-06-17 05:45:25易采站长站整理

│    │    │    │    └───── month (1 – 12)
│    │    │    └────────── day of month (1 – 31)
│    │    └─────────────── hour (0 – 23)
│    └──────────────────── minute (0 – 59)
└───────────────────────── second (0 – 59, OPTIONAL)

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、对象文本语法定时器

second (0-59)
minute (0-59)
hour (0-23)
date (1-31)
month (0-11)
year
dayOfWeek (0-6) Starting with Sunday


//每周一的下午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()方法即可