Search code examples
ruby-on-railsruby-on-rails-4herokurake

Rails, Rake scheduled tasks and DateTime with config.time_zone on Heroku


I seem to always struggle understanding this...

I have the Heroku scheduler running every 10m looking for new scheduled jobs to be run but it is not running when I expect it to - the difference is the time zone but I'm unclear exactly how I should do the comparison so it works the way I expect.

in the rake task we have:

schedules = Schedule.where('status in (?) and next_run < ?', ['new', nil, ''], DateTime.current)

in application.rb is

config.time_zone = 'Auckland'
config.active_record.default_timezone = :local

Now, the exact example I have just seen that didn't do what was expected was this:

  1. A user in NZ set up a schedule with a next_run time of Wednesday 18 February at 10am
  2. Based on the task above, this was actually run just after 9pm on Tuesday 17 February

Difference is the +13 hours for the NZ time zone.

Question is, how should I do this comparison to get the schedule to fire when I am expecting?

UPDATE 1: So after a bit of messing about, a few specific items worked for me:

  1. as per the answer below, I set the server timezone to the one I want
  2. I have removed the default_timezone entry form the config file - THIS WAS REALLY MESSING UP MY HEAD!
  3. Replaced all the various combinations of Date.now, Date.current, Time.now, Time.current, DateTime.now, Date.today etc. etc. with two specific replacements: Time.zone.today (and similar) and Time.zone.now (see this blog for all the juicy details http://danilenko.org/2012/7/6/rails_timezones/)

Solution

  • Use heroku env variable to set the default time zone:

    heroku config:add TZ="America/Los_Angeles" # example for Los Angeles
    

    I suppose, for your case it would be:

    heroku config:add TZ="Pacific/Auckland"