11

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!

user192249
  • 443
  • 2
  • 6
  • 16

1 Answers1

20

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.

MrTheWalrus
  • 9,670
  • 2
  • 42
  • 66
  • Thanks! Do I need to create a tasks file to store the method or can I just add the method in the schedule.rb file? For example, I want to call a certain method every minute, can I just type "every 1.minute do ........ end" ? – user192249 Sep 26 '12 at 18:01
  • @user192249 You don't need any special file besides schedule.rb - although I do make all my tasks into class methods on one or another class. Just call them using `runner`, as above. – MrTheWalrus Sep 26 '12 at 19:04