简体   繁体   中英

Setting up node-cron to run with Hubot

I'm trying to setup Hubot to run a cronjob but for some reason, the cronjob using node-cron is not firing. I've read and implemented things a few different ways (one example: https://leanpub.com/automation-and-monitoring-with-hubot/read ) but nothing seems to work. Currently the code I'm using is

module.exports = (robot) ->
  cronJob = require('cron').CronJob
  tz = 'America/Los_Angeles'
  pattern = '*/1 * * * *'
  cronjob = new cronJob(pattern, everyMinute, null, true, tz)

  console.log "reading cron"
  room = "#testing"
  robot.messageRoom room, 'startup message'

  everyMinute = ->
    robot.messageRoom '#testing', 'I will nag you every minute'
    console.log "every minute should be executed"

I see the startup messages but the messages in everyMinute don't come up in the room or the log. I've tried different formats for the pattern but haven't had any luck.

What's odd is hubot-cron ( https://github.com/miyagawa/hubot-cron ) works fine. I can setup a job and see the output message from a cronjob so I know it works. If I look through the hubot-cron source, I see

start: (robot) ->
    @cronjob = new cronJob(@pattern, =>
      @sendMessage robot
    , null, false, @timezone)
    @cronjob.start()

This looks like what I'm doing but hubot-cron works and my code doesn't. Any ideas?

It turns out that node-cron didn't like the way I was passing that function. Looks like the proper way to pass a function to node-cron is

module.exports = (robot) ->
  cronJob = require('cron').CronJob
  tz = 'America/Los_Angeles'
  pattern = '* * * * *'
  new cronJob(pattern, (->
    do everyMinute
  ), null, true, tz)

  everyMinute = ->
    console.log "every minute should be executed"

This works for me. Note that have the 'do everyMinute' on a separate line is necessary to avoid coffeescript complaining about a trailing comma.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM