0

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
Vaibhav Rajput
  • 189
  • 1
  • 2
  • 14

3 Answers3

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!

1

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

house9
  • 20,359
  • 8
  • 55
  • 61
  • This is not the delayed job. – Vaibhav Rajput Dec 08 '13 at 07:19
  • "execute cronjob or some rake task" - if you are executing ruby code, what I am saying is you can put that code into a Delayed Job object (move it out of rake task) and use the delayed job scheduling via `run_at` rails is much better at handling timezones and day light savings time than cron – house9 Dec 08 '13 at 16:29
  • This will be too expensive no? And also I don't want to take care of timezones of day light savings. Thanks Anyway. – Vaibhav Rajput Dec 09 '13 at 08:53
0

I know this is an old post but it just came up for me so I thought I'd chime in. I use the whenever gem for my cron jobs and have one that needs to execute every minute but only during US stock trading hours. In my schedule.rb I have:

every '*/1 09-17 * * *' do 
 rake "rake_namespace:rake_task"
end
abadfish
  • 81
  • 1
  • 4