Lenny-Hu / note

blog
5 stars 1 forks source link

Nodejs定时任务(node-schedule) #23

Open Lenny-Hu opened 5 years ago

Lenny-Hu commented 5 years ago

node-schedule https://github.com/node-schedule/node-schedule

需求

定时导出某些数据、定时发送消息或邮件给用户、定时备份什么类型的文件等等

使用

安装

npm install node-schedule

用法1:Cron风格定时器

*    *    *    *    *    *
┬    ┬    ┬    ┬    ┬    ┬
│    │    │    │    │    │
│    │    │    │    │    └ 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)

// 分钟为42时执行cron作业(例如19:42,20:42等)
var schedule = require('node-schedule');

var j = schedule.scheduleJob('42 * * * *', function(){
  console.log('The answer to life, the universe, and everything!');
});

6个占位符从左到右分别代表:秒、分、时、日、月、周几

* 表示通配符,匹配任意,当秒是*时,表示任意秒数都触发,其它类推

下面可以看看以下传入参数分别代表的意思

每分钟的第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'

每5分钟执行一次cron作业:  * / 5 * * * *

每个参数还可以传入数值范围:

const task1 = ()=>{
  //每分钟的1-10秒都会触发,其它通配符依次类推
  schedule.scheduleJob('1-10 * * * * *', ()=>{
    console.log('scheduleCronstyle:'+ new Date());
  })
}

task1()

用法2:基于时间(Date)

// 在2012年11月21日5:30执行
var schedule = require('node-schedule');
var date = new Date(2012, 11, 21, 5, 30, 0);

var j = schedule.scheduleJob(date, function(){
  console.log('The world is going to end today.');
});

用法3:定期规则调度

每小时的42分时触发

var schedule = require('node-schedule');

var rule = new schedule.RecurrenceRule();
rule.minute = 42;

var j = schedule.scheduleJob(rule, function(){
  console.log('The answer to life, the universe, and everything!');
});

您还可以使用数组指定可接受值的列表,使用Range对象指定起始值和结束值的范围,并使用可选的步骤参数。 例如,这将在周四,周五,周六和周日下午5点打印消息

var rule = new schedule.RecurrenceRule();
rule.dayOfWeek = [0, new schedule.Range(4, 6)];
rule.hour = 17;
rule.minute = 0;

var j = schedule.scheduleJob(rule, function(){
  console.log('Today is recognized by Rebecca Black!');
});

RecurrenceRule 属性列表

用法4:对象字面量语法

在每个周日下午2:30记录一条消息

var j = schedule.scheduleJob({hour: 14, minute: 30, dayOfWeek: 0}, function(){
  console.log('Time for tea!');
});

设置开始时间和结束时间,在此示例中,它将在5秒后运行并在10秒后停止

let startTime = new Date(Date.now() + 5000);
let endTime = new Date(startTime.getTime() + 5000);
var j = schedule.scheduleJob({ start: startTime, end: endTime, rule: '*/1 * * * * *' }, function(){
  console.log('Time for tea!');
});

取消定时器

调用 定时器对象的cancl()方法即可

const schedule = require('node-schedule');

function scheduleCancel(){

    var counter = 1;
    const j = schedule.scheduleJob('* * * * * *', function(){

        console.log('定时器触发次数:' + counter);
        counter++;

    });

    setTimeout(function() {
        console.log('定时器取消')
      // 定时器取消
        j.cancel();   
    }, 5000);

}

scheduleCancel();