A cron job for rails: best practices?
What's the best way to run scheduled tasks in a Rails environment? Script/runner? Rake?
I'm using the rake approach (as supported by heroku)
With a file called lib/tasks/cron.rake ..
task :cron => :environment do
puts "Pulling new requests..."
EdiListener.process_new_messages
puts "done."
end
To execute from the command line, this is just "rake cron". This command can then be put on the operating system cron/task scheduler as desired.
Update this is quite an old question and answer! Some new info:
I've used the extremely popular Whenever on projects that rely heavily on scheduled tasks, and it's great. It gives you a nice DSL to define your scheduled tasks instead of having to deal with crontab format. From the README:
Whenever is a Ruby gem that provides a clear syntax for writing and deploying cron jobs.
Example from the 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
Assuming your tasks don't take too long to complete, just create a new controller with an action for each task. Implement the logic of the task as controller code, Then set up a cronjob at the OS level that uses wget to invoke the URL of this controller and action at the appropriate time intervals. The advantages of this method are you:
上一篇: 如何测试每周的cron工作?
下一篇: 铁轨的cron工作:最佳实践?