怎样用node.js做定时任务
真的很简单,首先要安装 node-schedule,命令 : npm install node-schedule
使用方法如下:
首先要引入 :
var schedule = require("node-schedule");
然后有几种简单的方法供大家选择:
1:确定的时间
var date = new Date(2016,11,29,21,50,0);
schedule.scheduleJob(date, function(){
console.log("博主很帅");
});
2:每小时的固定时间
例如:每小时的第30分钟执行
var rule = new schedule.RecurrenceRule();
rule.minute = 30;
var j = schedule.scheduleJob(rule, function(){
console.log("博主很帅");
});
3:一个星期中的某些天的某个时刻执行,
例如:周一到周日的22点执行
var rule = new schedule.RecurrenceRule();
rule.dayOfWeek = [0, new schedule.Range(1, 6)];
rule.hour = 22;
rule.minute = 0;
var j = schedule.scheduleJob(rule, function(){
console.log("博主很帅");
});
4:每秒执行
var rule = new schedule.RecurrenceRule();
var times = [];
for(var i=1; i<60; i++){
times.push(i);
}
rule.second = times;
var c=0;
var j = schedule.scheduleJob(rule, function(){
c++;
console.log(c);
});
还有一种超简单的cron风格定时器:
var schedule = require('node-schedule');
function scheduleCronstyle(){
schedule.scheduleJob('30 * * * * *', function(){
console.log('scheduleCronstyle:' + new Date());
});
}
scheduleCronstyle();
* * * * * * * 是什么呢?请看图
* * * * * *
┬ ┬ ┬ ┬ ┬ ┬
│ │ │ │ │ |
│ │ │ │ │ └ day of week (0 - 7) (0 or 7 is Sun)
│ │ │ │ └───── month (1 - 12)
│ │ │ └────────── day of month (1 - 31)
│ │ └─────────────── hour (0 - 23)
│ └──────────────────── minute (0 - 59)
└───────────────────────── second (0 - 59, OPTIONAL)
6个占位符从左到右分别代表:秒、分、时、日、月、周几
'*'表示通配符,匹配任意,当秒是'*'时,表示任意秒数都触发,其它类推
下面可以看看以下传入参数分别代表的意思
官网链接: https://www.npmjs.com/package/node-schedule每分钟的第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'