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:

  • the heroku cron service I referenced has since been replaced by Heroku Scheduler
  • for frequent tasks (esp. where you want to avoid the Rails environment startup cost) my preferred approach is to use system cron to call a script that will either (a) poke a secure/private webhook API to invoke the required task in the background or (b) directly enqueue a task on your queuing system of choice

  • 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:

  • Have full access to all your Rails objects just as in a normal controller.
  • Can develop and test just as you do normal actions.
  • Can also invoke your tasks adhoc from a simple web page.
  • Don't consume any more memory by firing up additional ruby/rails processes.
  • 链接地址: http://www.djcxy.com/p/66338.html

    上一篇: 如何测试每周的cron工作?

    下一篇: 铁轨的cron工作:最佳实践?