Sidekiq + Sidetiq recurrence every 2 hours?

randombits picture randombits · Jan 5, 2014 · Viewed 9.5k times · Source

I can't exactly find how to set my recurrence rule to initiate the job every 2 hours. Currently I have my job to run at 3am every day (I think) using something like this in my Sidekiq worker class:

recurrence do
  daily.hour_of_day(3)
end

What's the best way of making this run every 2 hours or every hour? This uses the icecube gem underneath the hood, I believe.

Answer

Pablo Cantero picture Pablo Cantero · Jan 5, 2014

Have you tried hourly(2)?

recurrence do
  hourly(2)
  # if you want to specify the exactly minute or minutes
  # `minute_of_hour(30, ...)`
  # hourly(2).minute_of_hour(30)
end

It is in the icecube's README, but I haven't tried it yet.

You could also do something like that:

recurrence do
  # set recurrence to [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22]
  daily.hour_of_day(*(0..23).to_a.select { |hour_of_day| hour_of_day.even? })
end

But IMHO hourly(2) is the better choice.

Another option without Sidetiq is to add self.perform_in(2.hours) before ending the perform method.

def perform
   # ...
   self.class.perform_in(2.hours)
end

UPDATE:

https://github.com/tobiassvn/sidetiq/wiki/Known-Issues

Unfortunately, using ice_cube's interval methods is terribly slow on start-up (it tends to eat up 100% CPU for quite a while) and on every recurrence run. This is due to it calculating every possible occurrence since the schedule's start time.

So, it is better to use the more explicit way:

recurrence { hourly.minute_of_hour(0, 15, 30, 45) }