nodejs 定时任务 node-schedule 库

巧了我就是萌 提交于 2020-08-17 12:01:00

     

node-schedule 是一个基于时间的调度,而不是基于区间的调度。你可以很容易的让他按照你的意思来干活,比如,你说“每五分钟来运行这个函数",你将发现setInterval要更容易使用,也是更适合的。但是如果你想说"运行这个函数在每个月的第三个星期二每个小时的20分和50分",你会发现你更想要Node Schedule组件。此外,Node Schedule 支持windows系统,不像cron并不支持。

注意 Node Schedule 是被设计来进行进程内调度,也就是说调度任务只能在你的脚本运行时才能有效以及调度将在执行成功后消失。如果你需要在你脚步  运行的时候调度任务,那就需要考虑使用cron.

任务和调度

每个在Node Schedule的计划任务都会被一个Job对象所代表,你可手动创建任务,然后执行 schedule()方法来应用一个计划,或者使用一个方便的方法ScheduleJob() 就像下面要说的。

Job 对象是 事件触发器,触发一个 run 事件在每次执行之后。
他们也触发一个scheduled事件,在每次他们调度运行的时候,
canceled事件可以让一个调用在它执行之前被取消(这两个事件都接受一个JavaScript日期对象作为一个参数). 注意这个任务会第一时间被调度,所以如果你使用 scheduleJob()这个方便的方法来创建一个任务,你将错过第一个scheduled事件,但是你能手动查询调用(下面会有)。也要注意 canceled 是单L美式拼写方法

 

 

Node Schedule is a flexible cron-like and not-cron-like job scheduler for Node.js. It allows you to schedule jobs (arbitrary functions) for execution at specific dates, with optional recurrence rules. It only uses a single timer at any given time (rather than reevaluating upcoming jobs every second/minute).

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

 安装:

npm install node-schedule --save 或者 yarn add node-schedule

 

用法

1、Cron风格定时器

const schedule = require('node-schedule'); const scheduleCronstyle = ()=>{ //每分钟的第30秒定时执行一次: schedule.scheduleJob('30 * * * * *',()=>{ console.log('scheduleCronstyle:' + new Date()); }); } scheduleCronstyle(); 

schedule.scheduleJob的回调函数中写入要执行的任务代码,一个定时器就完成了!

规则参数讲解 *代表通配符
*  *  *  *  * * ┬ ┬ ┬ ┬ ┬ ┬ │ │ │ │ │ | │ │ │ │ │ └ 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个占位符从左到右分别代表:秒、分、时、日、月、周几

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

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

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

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

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

Recurrence Rule Scheduling

You can build recurrence rules to specify when a job should recur. For instance, consider this rule, which executes the function every hour at 42 minutes after the hour:

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!'); });

You can also use arrays to specify a list of acceptable values, and the Range object to specify a range of start and end values, with an optional step parameter. For instance, this will print a message on Thursday, Friday, Saturday, and Sunday at 5pm:

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 properties

  • second (0-59)
  • minute (0-59)
  • hour (0-23)
  • date (1-31)
  • month (0-11)
  • year
  • dayOfWeek (0-6) Starting with Sunday

Note: It's worth noting that the default value of a component of a recurrence rule is null (except for second, which is 0 for familiarity with cron). If we did not explicitly set minute to 0 above, the message would have instead been logged at 5:00pm, 5:01pm, 5:02pm, ..., 5:59pm. Probably not what you want.

使用方法

1:确定时间

    例如:2014年2月14日,15:40执行

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

    var date = new Date(2014,2,14,15,40,0);

    var j = schedule.scheduleJob(date, function(){

    console.log("执行任务");

  });

    取消任务

    j.cancel();

 

2:每小时的固定时间

  例如:每小时的40分钟执行

  var rule = new schedule.RecurrenceRule();

  rule.minute = 40;

  var j = schedule.scheduleJob(rule, function(){

    console.log("执行任务");

  });

3:一个星期中的某些天的某个时刻执行,

  例如:周一到周日的20点执行

  var rule = new schedule.RecurrenceRule();

  rule.dayOfWeek = [0, new schedule.Range(1, 6)];

  rule.hour = 20;

  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);
  });



 不能用rule.second=1 ;这样只是每分钟的第1秒去执行。 

 
// 指定多个规则
// 推荐使用 `Recurrence Rule Scheduling` 风格,便于理解
const Rule1 = new schedule.RecurrenceRule() const Rule2 = new schedule.RecurrenceRule() // Rule1 是每小时的 10分/33分/50分执行 Rule1.minute = [10, 33, 50] // Rule2 是每天10点/14点/20点的01分/10分/30分 执行 Rule2.hour = [10, 14,20] Rule1.minute = [1, 10, 30]

不支持的cron特性

一般的, W (最近的工作日), L (一个月/星期的最后一天), 以及 # (月的第n个星期) 是不支持的. 大多数流行的cron特性应该都能工作。

cron-parser 用来解析crontab指令

 

 

 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!