问题
I'm currently creating a rails application and would like to find out how to schedule certain tasks to run at a specific time.
For e.g. An admin would want to send emails to his users at 8:00am in the morning and does not want to wake up early just to send that email. Therefore, he/she would want to schedule the task to send emails at that time.
So, is there a way, or better still a gem, that allows tasks to be scheduled to run at a specific time? Thanks!
回答1:
My preferred solution here is the Whenever gem.
With it, you have schedule.rb
file, which specifies when certain things should be done, including running rake tasks, executing methods, or even executing arbitrary shell commands:
Example schedule.rb file, shamelessly copied from the Whenever readme:
every 3.hours do
runner "MyModel.some_process"
rake "my:rake:task"
command "/usr/bin/my_great_command"
end
every 1.day, :at => '4:30 am' do
runner "MyModel.task_to_run_at_four_thirty_in_the_morning"
end
every :hour do # Many shortcuts available: :hour, :day, :month, :year, :reboot
runner "SomeModel.ladeeda"
end
every :sunday, :at => '12pm' do # Use any day of the week or :weekend, :weekday
runner "Task.do_something_great"
end
every '0 0 27-31 * *' do
command "echo 'you can use raw cron syntax too'"
end
# run this task only on servers with the :app role in Capistrano
# see Capistrano roles section below
every :day, :at => '12:20am', :roles => [:app] do
rake "app_server:task"
end
I use Whenever for a number of tasks, including sending daily emails.
来源:https://stackoverflow.com/questions/12605976/schedule-rails-task-to-run-at-a-certain-time