在實(shí)際開發(fā)項(xiàng)目中,會遇到很多定時(shí)任務(wù)的工作。比如:定時(shí)導(dǎo)出某些數(shù)據(jù)、定時(shí)發(fā)送消息或郵件給用戶、定時(shí)備份什么類型的文件等等
一般可以寫個定時(shí)器,來完成相應(yīng)的需求,在node.js中自已實(shí)現(xiàn)也非常容易,接下來要介紹的是node-schedule來完成定時(shí)任務(wù)
下面就用示例來說明一下node-schedule的用法。
安裝
npm install node-schedule --save 或者 yarn add node-schedule
用法
1、Cron風(fēng)格定時(shí)器
const schedule = require('node-schedule');
const scheduleCronstyle = ()=>{
//每分鐘的第30秒定時(shí)執(zhí)行一次:
schedule.scheduleJob('30 * * * * *',()=>{
console.log('scheduleCronstyle:' + new Date());
});
}
scheduleCronstyle();
schedule.scheduleJob的回調(diào)函數(shù)中寫入要執(zhí)行的任務(wù)代碼,一個定時(shí)器就完成了!
規(guī)則參數(shù)講解 *代表通配符
* * * * * *
┬ ┬ ┬ ┬ ┬ ┬
│ │ │ │ │ |
│ │ │ │ │ └ 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個占位符從左到右分別代表:秒、分、時(shí)、日、月、周幾
*表示通配符,匹配任意,當(dāng)秒是*時(shí),表示任意秒數(shù)都觸發(fā),其它類推
下面可以看看以下傳入?yún)?shù)分別代表的意思
每分鐘的第30秒觸發(fā): '30 * * * * *'
每小時(shí)的1分30秒觸發(fā) :'30 1 * * * *'
每天的凌晨1點(diǎn)1分30秒觸發(fā) :'30 1 1 * * *'
每月的1日1點(diǎn)1分30秒觸發(fā) :'30 1 1 1 * *'
2016年的1月1日1點(diǎn)1分30秒觸發(fā) :'30 1 1 1 2016 *'
每周1的1點(diǎn)1分30秒觸發(fā) :'30 1 1 * * 1'
每個參數(shù)還可以傳入數(shù)值范圍:
const task1 = ()=>{
//每分鐘的1-10秒都會觸發(fā),其它通配符依次類推
schedule.scheduleJob('1-10 * * * * *', ()=>{
console.log('scheduleCronstyle:'+ new Date());
})
}
task1()
2、對象文本語法定時(shí)器
const schedule = require('node-schedule');
function scheduleObjectLiteralSyntax(){
//dayOfWeek
//month
//dayOfMonth
//hour
//minute
//second
//每周一的下午16:11分觸發(fā),其它組合可以根據(jù)我代碼中的注釋參數(shù)名自由組合
schedule.scheduleJob({hour: 16, minute: 11, dayOfWeek: 1}, function(){
console.log('scheduleObjectLiteralSyntax:' + new Date());
});
}
scheduleObjectLiteralSyntax();
3、取消定時(shí)器
調(diào)用 定時(shí)器對象的cancl()方法即可
const schedule = require('node-schedule');
function scheduleCancel(){
var counter = 1;
const j = schedule.scheduleJob('* * * * * *', function(){
console.log('定時(shí)器觸發(fā)次數(shù):' + counter);
counter++;
});
setTimeout(function() {
console.log('定時(shí)器取消')
// 定時(shí)器取消
j.cancel();
}, 5000);
}
scheduleCancel();