Heroku Scheduler - 设置日常任务

时间:2014-10-21 14:58:06

标签: ruby-on-rails heroku twilio scheduler rake-task

我无法理解Heroku的调度程序文档。

他们将此作为示例代码,但我不确定它是什么:

desc "This task is called by the Heroku scheduler add-on"
task :update_feed => :environment do
  puts "Updating feed..."
  NewsFeed.update
  puts "done."
end

task :send_reminders => :environment do
  User.send_reminders
end

我希望每天使用此调度程序从我的NotificationsController调用方法。我尝试将代码修改为:

desc "This task is called by the Heroku scheduler add-on"
task notify: :environment do
  Notifications.notify
end

我的notifications_controller.rb看起来像: 注意包含Twilio API的集成......这也将在未来重构,但它确实可以用于测试。

class NotificationsController < ApplicationController
    require 'twilio-ruby'

    skip_before_action :verify_authenticity_token
    before_action :set_twilio_client

    $numbers = []
    User.all.select {|user| $numbers << user.phone_number}


    def daily_text
        $daily_text = ["Test 1", "Test 2", "Test 3"]
        $daily_text.sample
    end

    def notify
        message = @client.messages.create(
            from: '+1401XXXXXXX',
            to: $numbers,
            body: daily_text
            )

        render plain: message.status
    end

    private

    def set_twilio_client
        twilio_account_sid = ENV["TWILIO_ACCOUNT_SID"]
        twilio_auth_token = ENV["TWILIO_AUTH_TOKEN"]
        @client = Twilio::REST::Client.new twilio_account_sid, twilio_auth_token
    end

end

也许我需要将一些东西移到模型级别?任何指导都表示赞赏。

1 个答案:

答案 0 :(得分:0)

我重构并将大部分内容转移到TwilioClient模型中:

class TwilioClient
    require 'twilio-ruby'

    def initialize
        @client = Twilio::REST::Client.new ENV["TWILIO_ACCOUNT_SID"], ENV["TWILIO_AUTH_TOKEN"]
    end

    def notify
        @client.messages.create(
            from: '+1401XXXXXXX',
            to: all_phone_numbers,
            body: daily_text
        )
    end

    private

    def daily_text
        ["Test 1", "Test 2", "Test 3"].sample
    end

    def all_phone_numbers
        User.pluck(:phone_number)
    end

end

通知控制器现在看起来像:

class NotificationsController < ApplicationController
    skip_before_action :verify_authenticity_token

    def notify
        client = TwilioClient.new
        result = client.notify
        render plain: result.status
    end
end

和rake任务:

desc "This task is called by the Heroku scheduler add-on"
task notify: :environment do
  client = TwilioClient.new
  client.notify
end