Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have a cronjob starting a ruby script (in a rails environment) at the beginning of each hour. The ruby script then makes a series of SQL queries, and looks like this:

def hourly_job
  time = Time.now - 1.hour
  date = time.to_date
  hour = time.hour
  start_time = date.to_time + hour.hours
  end_time = start_time + 1.hour

  Log.where(date: date, hour: hour).delete_all
  count = Event.where('created_at >= ?', start_time).
    where('created_at < ?', end_time).count
  Log.create(date: date, hour: hour, count: count)
end

The cronjob looks like this (generated by the whenever gem):

0 * * * * /bin/bash -l -c 'cd /path/to/myproj && script/rails runner '\''Log.hourly_job'\'''

This seemed to work fine for a few weeks, but this morning I found that the log table is empty -- something has erased all of my past data, in addition to not logging hourly data until a few hours ago.

An inspection of the MySQL error log revealed no events in the last week, and all of the other table's data seems to be fine, so I don't think it's a DBMS problem.

I'm suspecting some sort of discrepancy between the time that crontab is using and the time given by ruby's Time.now. I'm also exploring the idea that there is something subtly and horribly wrong with my code.

Are there other possible explanations?

Additionally, I am running this project on two separate servers. This data erasing bug has only hit one of them.

share|improve this question

closed as off-topic by Jeff Vanzella, Uri Agassi, Marc-Andre, rolfl, syb0rg Feb 27 at 21:47

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Your question must contain working code for us to review it here. For questions regarding specific problems encountered while coding, try Stack Overflow. After getting your code to work, you may edit this question seeking a review of your working code." – Uri Agassi, Marc-Andre, rolfl, syb0rg
If this question can be reworded to fit the rules in the help center, please edit the question.

add comment

1 Answer 1

Could it be related to timezones? Did daylight savings recently kick in for you locally?

I try to avoid time related accidents by always storing and using UTC, and only converting to local time on display.

Time.now.utc

To find the root-cause, I'd look at the rails log and find the sql that was used in that delete_all and examine the parameters more closely.

share|improve this answer
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.