简体   繁体   中英

Inconsistent behavior of Time.now in Ruby/Rails app

I have a Ruby on Rails app that has a scheduled job I execute using cron and script/runner.

The purpose of the job is to find any updates that are past due ('stale', see below) and (after executing the job) update the 'due date' of the job a pre-defined number of minutes into the future.

The problem I'm having is that when I set the 'due date', the "GMT" time is used. However, when I search for stale jobs, the 'local' time seems to be used. The local time of the server is -7 hours offset from GMT, so the system goes 7 extra hours between updates.

Example: The due date of the job is 06:00 on a certain day. The system finds that job at 06:00 west coast time (-7 GMT). If the job is due again in 15 mins, it sets the 'due date' to 06:15 which gets changed to 13:15 when the object is saved (15 mins and 7 hours into the future).

I'll insert the code below. If it makes any difference, 'mark_updated' is part of a model and self.stale is a class-level function in a module that is included in the same model.

BTW...bonus question - how to get catch the SQL that is being executed from script/runner job in Production? That would make this easier to debug. I'm guessing a little at what is happening.

def mark_updated
  self.next_refresh_due_at = Time.now + update_interval_in_minutes.minutes
  save
end

def self.stale(max = 3)
  news_sources = NewsSource.find(:all,
                               :conditions => ["next_refresh_due_at < ?", Time.now],
                               :order => 'next_refresh_due_at ASC',
                               :limit => max)

  return news_sources
end

I'm assuming you have the time zone specified in your environment.rb config file. In that case you should use Time.zone.now instead of Time.now .

See this answer for a full explanation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM