How does Hubot run a function regularly without any command?

I am trying to make a function for hubot to send a message every 5 minutes to a room without any command, only by myself.

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

What do i need to change?

+4
source share
3 answers

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

+6
source

In fact, the hubot documentation shows the use of setInterval()and setTimeout()without the use of additional modules.

You can even do this inline by binding to the msg object. For instance:

module.exports = (robot) ->
  updateId = null

  robot.respond /start/i, (msg) ->
      msg.update = () ->                        # this is your update
          console.log "updating"                # function

      if not this.updateId                      # and here it
          this.updateId = setInterval () ->     # gets
             msg.update()                       # periodically
          , 60*1000                             # triggered minutely
          msg.send("starting")
+2

, msg.send . robot.messageRoom ( , ).

0

All Articles