安装扩展:node-schedule
npm install node-schedule
1、linux Crontab风格
var schedule = require('node-schedule'); function scheduleCron(){
schedule.scheduleJob('1 * * * * *', function(){
console.log('Hello World');
});
} scheduleCron();
通配符解释:
* * * * * *
┬ ┬ ┬ ┬ ┬ ┬
│ │ │ │ │ |
│ │ │ │ │ └ [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) 秒
范围内执行:
function scheduleCron(){
schedule.scheduleJob('1-10 * * * * *', function(){
console.log('每分钟的1-10秒执行');
});
}
2、对象风格:
var schedule = require('node-schedule'); function scheduleRule(){
var rule = new schedule.RecurrenceRule(); rule.dayOfWeek = 5; // 周几
rule.month = 4; // 月
rule.dayOfMonth = 3; // 日
rule.hour = 2; // 时
rule.minute = 1; // 分
rule.second = 0; // 秒 schedule.scheduleJob(rule, function(){
console.log('hello world');
}); }
scheduleRule()
间隔执行:rule 规则传入数组即可
var schedule = require('node-schedule'); function scheduleRule(){
var rule = new schedule.RecurrenceRule(); // 每隔2秒执行
// 分、时、等同理
rule.second = [1,3,5,7]; schedule.scheduleJob(rule, function(){
console.log('hello world');
}); }
3、按确定的时间执行:
2017年7月12号14:50:00执行==>
var schedule = require('node-schedule'); function scheduleDate(){ var date = new Date(2017,7,12,14,50,0);
schedule.scheduleJob(rule, function(){
console.log('hello world');
});
} scheduleDate();
4、取消定时任务:
var schedule = require('node-schedule'); function scheduleCancel(){ var counter = 1;
var j = schedule.scheduleJob('* * * * * *', function(){ console.log('定时器触发次数:' + counter);
counter++; }); setTimeout(function() {
console.log('定时器取消')
j.cancel();
}, 5000); } scheduleCancel();