Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you call a method every hour in Rails?

I'm using Resque with Redis to process a background job. I'd like to call the method, Resque.enqueue(MyModel) just one time every hour to do a background task.

For example: Say I have a site that has a 10,000 users. I would like to call this method only 24 times per day; not 10,000 * 24. The example method is below:

Resque.enqueue(MyModel)

Thank you for your help in advance. I should also mention I prefer to stick with Resque, and not move to Delayed Job. Thank you.

like image 453
JZ. Avatar asked May 22 '11 23:05

JZ.


2 Answers

You should use a cron job for this kind of task.

I suggest you use the Whenever gem.

See railscast here: http://railscasts.com/episodes/164-cron-in-ruby

like image 75
apneadiving Avatar answered Oct 12 '22 23:10

apneadiving


Since you are already using Resque, I would recommend to use one of the many available Resque plugins: resque-scheduler. Plugs into the Resque UI very nicely as well. Simple setup as explained in the README. Also adds a lot of the missing DelayedJob stuff (delayed execution).

Why I switched from whenever to resque-scheduler:

  • Stays in the app-folder and doesn't mess with your cron file.
  • To stop all 'crons' just disable the Resque workers.
  • Exceptions are logged to the Resque UI.
  • Manual rescheduling via the Resque UI possible.
  • In combination with resque-loner you prevent double-execution should a job take longer than the span between two executions.
  • Still obeys to the priority-system of Resque.
  • No additional boot-time (could take up to 60s if your app gets bigger) since it uses Resque's worker-pool.
  • One less "tech" used.
  • Simple switch: Configuration is done in a cron-like manner.
like image 40
Marcel Jackwerth Avatar answered Oct 12 '22 23:10

Marcel Jackwerth