Search code examples
hubot

How can Hubot run function regularly, without any command?


I'm trying to make a function for hubot send a message every 5 minutes to a room without any command, just by himself.

module.exports = (robot, scripts) ->
  setTimeout () ->
    setInterval () ->
      msg.send "foo"
    , 5 * 60 * 1000
  , 5 * 60 * 1000

What do I need to change?


Solution

  • Use node-cron.

    $ npm install --save cron time
    

    And your script should look like this:

    # Description:
    #   Defines periodic executions
    
    module.exports = (robot) ->
      cronJob = require('cron').CronJob
      tz = 'America/Los_Angeles'
      new cronJob('0 0 9 * * 1-5', workdaysNineAm, null, true, tz)
      new cronJob('0 */5 * * * *', everyFiveMinutes, null, true, tz)
    
      room = 12345678
    
      workdaysNineAm = ->
        robot.emit 'slave:command', 'wake everyone up', room
    
      everyFiveMinutes = ->
        robot.messageRoom room, 'I will nag you every 5 minutes'
    

    More details: https://leanpub.com/automation-and-monitoring-with-hubot/read#leanpub-auto-periodic-task-execution