Nodejs 定时任务

安装扩展:node-schedule

npm install node-schedule

1、linux Crontab风格

1 var schedule = require('node-schedule');
2 
3 function scheduleCron(){
4     schedule.scheduleJob('1 * * * * *', function(){
5         console.log('Hello World');
6     }); 
7 }
8 
9 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) 秒
范围内执行:
1 function scheduleCron(){
2     schedule.scheduleJob('1-10 * * * * *', function(){
3         console.log('每分钟的1-10秒执行');
4     }); 
5 }

2、对象风格:

 1 var schedule = require('node-schedule');
 2 
 3 function scheduleRule(){
 4     var rule = new schedule.RecurrenceRule();
 5 
 6     rule.dayOfWeek = 5;     // 周几
 7     rule.month = 4;        // 月 
 8     rule.dayOfMonth = 3;    // 日
 9     rule.hour = 2;          // 时
10     rule.minute = 1;       // 分   
11     rule.second = 0;        // 秒    
12     
13     schedule.scheduleJob(rule, function(){
14         console.log('hello world');
15     });
16    
17 }
18 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、取消定时任务:

 1 var schedule = require('node-schedule');
 2 
 3 function scheduleCancel(){
 4 
 5     var counter = 1;
 6     var j = schedule.scheduleJob('* * * * * *', function(){
 7         
 8         console.log('定时器触发次数:' + counter);
 9         counter++;
10         
11     });
12 
13     setTimeout(function() {
14         console.log('定时器取消')
15         j.cancel();   
16     }, 5000);
17     
18 }
19 
20 scheduleCancel();