LoginSignup
79
75

More than 5 years have passed since last update.

Hubot × node-cron で、定刻/定間隔に ○○ をさせる簡単な例

Posted at

実現したいことはタイトルの通りです。使いどころとしては、例えばお昼や就業時間の定時になったらチャットルームに通知、とかでしょうか。
もしくは開発プロセスにおいて、もし定期的に実施するタスクがあれば通知するとか。タスク自体を Hubot にやらせてもいいですね。

これらは Node.js の node-cron を利用すれば簡単に実現できます。

Hubot の作り方や環境まわり(Heroku や Yeoman)については、以前に書いた投稿を参考にしてください。
Hubot を Twitter の公開タイムラインに住まわせる
Yoeman で Hubot を作成して Heroku へデプロイし Slack と連携する

cron は、Node.js 用のこれを使います。現時点のバージョンは 1.0.5 です。
https://github.com/ncb000gt/node-cron

手順

node-cron の npm パッケージを導入

Yoeman で 雛形を作成したら、package.json に下記を追記します。

package.json
{
  "name": "hubot-twibot",
  "version": "0.0.1",
  "private": true,
  "author": "Hiroyuki Kusu <kusu0806@gmail.com>",
  "description": "A simple helpful robot for your Company",
  "dependencies": {
    "hubot": "^2.9.3",
    "hubot-diagnostics": "0.0.1",
    "hubot-google-images": "^0.1.0",
    "hubot-google-translate": "^0.1.0",
    "hubot-help": "^0.1.1",
    "hubot-heroku-keepalive": "0.0.4",
    "hubot-maps": "0.0.0",
    "hubot-pugme": "^0.1.0",
    "hubot-redis-brain": "0.0.2",
    "hubot-rules": "^0.1.0",
    "hubot-scripts": "^2.5.16",
    "hubot-shipit": "^0.1.1",
    "hubot-youtube": "^0.1.2",
+    "cron": "^1.0.5"
  },
  "engines": {
    "node": "0.10.x"
  }
}

追記してファイルを保存したら、コンソールで $ npm install します。

cron のジョブと、実行させたいタスクを記載する

CronJob クラスを冒頭で require し、これを new でインスタンス化する際に引数で、ジョブの設定を行います。

scripts/cron_tweet.coffee
CronJob = require("cron").CronJob

taskA = ->
  console.log "This is task A"
  # ..

taskB = ->
  console.log "This is task B"
  #..

taskC = ->
  console.log "This is task C"
  #..

job = new CronJob(
  cronTime: "*/10 * * * * *"
  onTick: ->
    taskA()
    taskB()
    taskC()
    return
  start: false
)

cronTime キーの値に、スペース区切りで「秒」「分」「時」「日」「月」「週」の設定を書きます。

詳しくは node-cron のページを参照ください。
https://github.com/ncb000gt/node-cron

onTick キーの値(function)で、実行したいタスクを羅列すればOKです。

もしチャット経由で cron ジョブの開始/停止を指示したい場合は、次のように robot.respond を契機として job.start() job.stop() をすればいいです。

scripts/cron_tweet.coffee


module.exports = (robot) ->

  robot.respond /start job/i, (msg) ->
    msg.send "Start job.."
    job.start()

  robot.respond /stop job/i, (msg) ->
    msg.send "Stop job.."
    job.stop()

もし自動で ジョブを開始したい場合は、CronJob クラスのインスタンス化の引数で、start キーの値に true を指定しておけばOKです。

〜おしまい〜

79
75
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
79
75