【问题标题】:Using node-cron with coffeescript将 node-cron 与咖啡脚本一起使用
【发布时间】:2016-02-26 06:16:37
【问题描述】:

我正在尝试为使用 node-cron 的 hubot 编写一个咖啡脚本。我找到了一个这样的例子,效果很好:

module.exports = (robot) ->
  cronJob = require('cron').CronJob
  new cronJob('0 */1 * * * *', everyMinute(robot), null, true)

everyMinute = (robot) ->
  -> robot.messageRoom '#billing', 'hey brah!'

但是,这是我当前的脚本。它似乎永远不会触发节点事件。我基本上每分钟都在尝试检查远程 API 的状态并将结果设置在 hubot 的大脑中。我在这里做错了什么?这基本上是我写的第一个coffeescript,所以仍然找到我的脚。

module.exports = (robot) ->

  cronJob = require('cron').CronJob
  new cronJob('0 */1 * * * *', getOnPoint, null, true)

  getOnPoint = ->
    robot.http("https://#{pagerDutyDomain}.pagerduty.com/api/v1/schedules/#{pagerDutyService}")
    .headers(Authorization: "Token token=\"#{pagerDutyToken}\"", Accept: 'application/json')
      .query(since: '2015-11-23T21:15:49Z', until: '2015-11-23T22:15:49Z')
      .get() (err,res,body) ->
        if res.statusCode isnt 200
          msg.send "Request didn't come back HTTP 200 :( got back #{body}"
          return

        json = JSON.parse(body)
        onpoint_person = json.schedule.final_schedule.rendered_schedule_entries[0].user.email
        robot.logger.debug "Setting onpoint to #{onpoint_person}"
        robot.brain.set 'onpoint_person', onpoint_person.split("@")[0]

我查看了coffeescript编译成的JS,很明显我声明函数的方式很重要,但我不知道为什么。

非常感谢任何帮助。

【问题讨论】:

  • getOnPoint 从未被调用过?
  • 不是在cronjob里面调用吗? new cronJob('0 */1 * * * *', getOnPoint, null, true)
  • “它似乎永远不会触发节点事件”是什么意思?哪个活动?
  • 嗯,它似乎没有做“任何事情”。我尝试将代码更改为:cronJob = require('cron').CronJob new cronJob('0 */1 * * * *', robot.emit "testing", null, true) 每 1 分钟调用一次的函数永远不会被执行..
  • 第一次通话发生在 1 分钟后。尝试使用* * * * * * 进行测试。它应该每秒调用一次。

标签: javascript node.js coffeescript cron


【解决方案1】:

我遇到了同样的问题,如果您注意到他的方法中有两个 ->,我通过在 cronJob 和您要使用的方法之间创建另一种方法来解决这个问题。

new cronJob('0 */1 * * * *', getOnPointMethod(), null, true)

getOnPointMethod = ->
  -> getOnPoint()

这将起作用,不知道它是多么优雅或好的解决方案,但它确实有效。

【讨论】:

    【解决方案2】:

    你需要将函数getOnPoint放在初始化cron之上

    【讨论】:

      猜你喜欢
      • 2016-01-05
      • 1970-01-01
      • 2011-11-08
      • 1970-01-01
      • 2013-02-03
      • 1970-01-01
      • 1970-01-01
      • 2015-06-30
      • 1970-01-01
      相关资源
      最近更新 更多