一. 安裝
npm install node-schedule
二. 使用
例子通過定時訪問url展示
首先引入2個模塊和訪問的方法:
- var http = require('http');
- var schedule = require("node-schedule");
- function httpGet(){
- var uri = `http://120.25.169.8/before/index`;
- http.get(uri, function(res) {
- console.log("訪問個人微博狀態碼: " + res.statusCode);
- }).on('error', function(e) {
- console.log("個人微博 error: " + e.message);
- });
- }
1. 確定的時間執行
比如: 2016年7月13日15:50:00 , new Date() 的時候月份要減1.
- var date = new Date(2016,6,13,15,50,0);
- schedule.scheduleJob(date, function(){
- httpGet();
- });
比如:每5秒執行一次
- var rule1 = new schedule.RecurrenceRule();
- var times1 = [1,6,11,16,21,26,31,36,41,46,51,56];
- rule1.second = times1;
- schedule.scheduleJob(rule1, function(){
- httpGet();
- });

3.以分為單位執行
比如:每5分種執行一次
- var rule2 = new schedule.RecurrenceRule();
- var times2 = [1,6,11,16,21,26,31,36,41,46,51,56];
- rule2.minute = times2;
- schedule.scheduleJob(rule2, function(){
- httpGet();
- });
有500請忽略,不小心把數據庫關掉了.
4.以小時為單位執行
比如:每4小時執行一次
- var rule3 = new schedule.RecurrenceRule();
- var times3 = [1,5,9,13,17,21];
- rule3.hour = times3; rule1.minute = 0;
- schedule.scheduleJob(rule3, function(){
- httpGet();
- });
以小時的就不貼運行結果了.時間太久
5.Cron風格

- schedule.scheduleJob('5 * * * * *', function(){
- httpGet();
- });
這個代碼的意思就是每分鍾的5秒這個點執行

比較坑的就是如果項目中有定時任務的時候,開啟多線程模式就會執行多次,不管是這個模塊還是使用 setInterval,有能解決的大神請留言.