问题
I'm having trouble understanding Heroku's scheduler documentation.
They give this as example code, but I'm not sure what's what:
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
I am hoping to use this scheduler to call method from my NotificationsController on a daily basis. I've tried modifying their code to:
desc "This task is called by the Heroku scheduler add-on"
task notify: :environment do
Notifications.notify
end
My notifications_controller.rb looks like: Notice integration of Twilio's API is included...also this will be refactored down the road, but it does work in testing.
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
Maybe I need to move some stuff up to model level? Any guidance is appreciated.
回答1:
I refactored and moved most things into a TwilioClient model:
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
Notifications Controller now looks like:
class NotificationsController < ApplicationController
skip_before_action :verify_authenticity_token
def notify
client = TwilioClient.new
result = client.notify
render plain: result.status
end
end
and rake task:
desc "This task is called by the Heroku scheduler add-on"
task notify: :environment do
client = TwilioClient.new
client.notify
end
来源:https://stackoverflow.com/questions/26489818/heroku-scheduler-set-up-daily-task