A cron job for rails: best practices?

2019-01-02 16:40发布

What's the best way to run scheduled tasks in a Rails environment? Script/runner? Rake?

20条回答
有味是清欢
2楼-- · 2019-01-02 17:03

you can use resque and resque-shheduler gem for creating crons, this is very easy to do.

https://github.com/resque/resque

https://github.com/resque/resque-scheduler

查看更多
泛滥B
3楼-- · 2019-01-02 17:04

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
查看更多
明月照影归
4楼-- · 2019-01-02 17:04

I'm a big fan of resque/resque scheduler. You can not only run repeating cron-like tasks but also tasks at specific times. The downside is, it requires a Redis server.

查看更多
怪性笑人.
5楼-- · 2019-01-02 17:05

Once I had to make the same decision and I'm really happy with that decision today. Use resque scheduler because not only a seperate redis will take out the load from your db, you will also have access to many plugins like resque-web which provides a great user interface. As your system develops you will have more and more tasks to schedule so you will be able to control them from a single place.

查看更多
素衣白纱
6楼-- · 2019-01-02 17:09

Using something Sidekiq or Resque is a far more robust solution. They both support retrying jobs, exclusivity with a REDIS lock, monitoring, and scheduling.

Keep in mind that Resque is a dead project (not actively maintained), so Sidekiq is a way better alternative. It also is more performant: Sidekiq runs several workers on a single, multithread process while Resque runs each worker in a separate process.

查看更多
萌妹纸的霸气范
7楼-- · 2019-01-02 17:10

Probably the best way to do it is using rake to write the tasks you need and the just execute it via command line.

You can see a very helpful video at railscasts

Also take a look at this other resources:

查看更多
登录 后发表回答