Rails Execute Cron Job or Rake task for specific time period

吃可爱长大的小学妹 提交于 2019-12-08 11:40:32

问题


I want to execute some task for a specific time period. Lets say I want to execute cronjob or some rake task between 6am to 9am for every half an hour. So script will get execute 6, 6:30, 7, 7:30... and last at 9.

Can you please give me some suggestion that how I can do this with Rails.

Don't tell me that schedule individual task for 6, 6:30, 7.. time period.

ANS
Simplest way I have found is to use whenever gem and adding cronjob time as below.

every '*/30 6-9 * * *' do
  runner "Model.method"
end

回答1:


One of the easiest ways to do this is via the Ruby gem called whenever. It provides you a really nice DSL (domain-specific language) you can use in order to do exactly what you want. I've used it before for server app deployments, and it's worked like a charm!

Here is a link to the gem repository on Github:
https://github.com/javan/whenever

Here is also a great RailsCast you can watch on how to set it up in Rails: http://railscasts.com/episodes/164-cron-in-ruby


You should be able to do something like this:

every :day, :at => (6..8).to_a.map { |x| ["#{x}:00","#{x}:30", "#{x+1}:00"] }.flatten do
  # Run rake task.
end

# => ["6:00", "6:30", "7:00", "7:00", "7:30", "8:00", "8:00", "8:30", "9:00"]

You can adjust the initial range and the inner block to cover any range you want. whenever conveniently handles military time format (24hr clock), which makes this great to use.

Hope that helps!




回答2:


I like to use delayed_job for scheduled tasks - https://github.com/collectiveidea/delayed_job

When you enque a job you can specify the run_at attribute



来源:https://stackoverflow.com/questions/20446343/rails-execute-cron-job-or-rake-task-for-specific-time-period

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!