nodejs 定時任務 node-schedule 庫


     

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指令

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM