node-schedule

node-schedule是一個time base的排程器,透過給定簡單的時間物件或是給與cron job的時間格式字串,就可以指定時間觸發所給定的task。 這在Java的世界,與一套叫Quartz的服務相像...

Github repository

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

Installation

npm install node-schedule

Sample Usage

下面範例展示一個簡單的排程作業,其中date指定為現在時間過30秒,而date2指定為一個未來的時間... 程式起動時候,會先列印現在時間,並開始設定兩個(j, j2) Job分別在指定的date, date2時間啟動...

var schedule = require('node-schedule');
var date = new Date(new Date().getTime() + 1*1000*30);
var date2 = new Date('2015/1/31 21:28:00');
console.log(new Date());

console.log('j will start at:', date);
var j = schedule.scheduleJob(date, function(){
        console.log('The job j is going to end...');
});

console.log('j2 will start at:',date2);
var j2 = schedule.scheduleJob(date2, function(){
        console.log('The job j2 is going to end...');
});

上面程式起動後,會執行列印現在時間,並且開始將Job置入排程時間,等候執行...

$ node examples/node-schedule/sample01.js
Sun Feb 01 2015 14:40:34 GMT+0800 (CST)
j will start at: Sun Feb 01 2015 14:41:03 GMT+0800 (CST)
j2 will start at: Sat Feb 2 2015 21:28:00 GMT+0800 (CST)
The job j2 is going to end...
(waitting...)

等到執行的時間到了,系統就會執行定義於j, j2中callback function中的內容... 等到所有Job執行完成,程式就會關閉...

除了標準時間格式之外,node-schedule也提供cron job的輸入方式,使用"分 時 日 月 星期"來作為時間輸入...

var cronjob = schedule.scheduleJob('*/5 * * * *', function(){
        console.log('The job will launch every 5 minutes...');
});

如果Job已經載入後,需要刪除,可以直接透過cancel的方法來刪除job...,官方提供的範例如下:

var job = schedule.scheduleJob(...);
job.cancel();

而在實作上,建議自己建立一個資料結構來收藏這些Job的資訊,例如: 資料庫,或是直接建立一個global的變數來收...

var jobs = {}

function createJob(jobid, jobtime) {
  jobs[jobid] = schedule.scheduleJob(jobtime, function(){
    // do something you want...
  });
}

function deleteJob(jobid) {
  jobs[jobid].cancel();
}

類似這樣的擺置,下次要操作Job的時候,就有一些依據了... :D

Sample Project

因為Schedule服務非常實用,筆者花了一些時間把這些動作建置成一個RESTful操控的服務器,透過簡單的動作,就可以提供RESTful的Endpoint來操控排程...

安裝服務

目前服務release在github上,有興趣使用的朋友可以直接git clone下來或是fork回去改...

$ git clone [email protected]:peihsinsu/node-schedule-server.git $project_home
$ cd $project_home && npm install

啟動服務

因為使用express 4來實作,因此可以透過npm start來啟動... 真正的啟動程式定義在package.json,位置為bin/www。

$ cd $project_home
$ npm start

撰寫服務執行者(Worker)

預設我只提供了一個RESTful Client來在排程時間到之後透過Url的方式來執行服務,這個RESTful Client(workers/restclient.js)的目的在使用前端傳入的opts參數內容來使用request模組來達到呼叫的目的。

每個Worker的必要條件如下:

  • 必須放置在$project_home/workers下面
  • 名稱必須與呼叫時候給定的"catg"參數值相同
  • 可參考restclient.js實作Worker:
    • 必須具備exec這個function
    • 這個 exec function 必須有一個opts的json字串輸入,這個值是由呼叫時候給訂opts參數傳入。
var request = require('request');
var log = require('nodeutil').simplelog;

exports.exec = function(opts) {
    if(typeof(opts) == 'string')
        opts = JSON.parse(opts);
  //Here you can do the job...
    request(opts, function(e, r, d) {
        if(e) log.error('Job[%s] execute error:', e);
        log.info('Job[%s] execute result:', d);
    });
}

新增加一筆服務

一切準備就緒後,在服務啟動完成,就可以透過下面方式呼叫新增一筆排程工作...

curl -X POST -sS http://127.0.0.1:3000/schedule/testjob \
  -d "jobtime=2015/2/1 1:59:00" \
  -d catg=restclient \
  -d 'opts={"url":"http://localhost:3000","method":"GET"}'

results matching ""

    No results matching ""