Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Schedule Rails Task to run at a certain time

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!

like image 576
user192249 Avatar asked Sep 26 '12 16:09

user192249


People also ask

How do I schedule a rake task?

You can choose to run your Rake tasks automatically or manually. Running them automatically involves either scheduling them by using the Rake task add-on or by using deploy hooks. Alternatively, you can run them manually on your server.

How do I schedule an executable to run?

Go to the Start menu search bar, type in 'task scheduler,' and select the best match. In the Task Scheduler menu, right-click on the Task Scheduler Library, and select New Folder… There, type a name for your folder and click on OK. Now expand the Task Schedule Library.


1 Answers

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.

like image 62
MrTheWalrus Avatar answered Jan 01 '23 23:01

MrTheWalrus