问题描述
我目前正在创建一个 rails 应用程序,并想了解如何安排某些任务在特定时间运行.
I'm currently creating a rails application and would like to find out how to schedule certain tasks to run at a specific time.
例如管理员希望在早上 8:00 向他的用户发送电子邮件,并且不想为了发送该电子邮件而早起.因此,他/她会想要安排任务在那个时间发送电子邮件.
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.
那么,有没有一种方法,或者最好还是一个 gem,允许将任务安排在特定时间运行?谢谢!
So, is there a way, or better still a gem, that allows tasks to be scheduled to run at a specific time? Thanks!
推荐答案
我的首选解决方案是 Whenever 宝石.
My preferred solution here is the Whenever gem.
有了它,你就有了 schedule.rb
文件,它指定什么时候应该完成某些事情,包括运行 rake 任务、执行方法,甚至执行任意 shell 命令:
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:
示例 schedule.rb 文件,无耻地从 Every readme 复制而来:
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
我使用 When 来完成许多任务,包括每天发送电子邮件.
I use Whenever for a number of tasks, including sending daily emails.
这篇关于安排 Rails 任务在特定时间运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!