3

I want to perform some actions on a user when it's midnight in his or her region. Since I want to support time zones instead of basing everything on server time, I want to cover all the possible midnights of every time zone.

The idea I had so far is to create a rake task that is triggered every hour with cron, and the rake task tries to figure out what time zone just ticked over to midnight. This is a pretty unreliable approach, especially when a time zone enters DST.

Are there any other more reliable ways to accomplish this?

Gyt Dau
  • 35
  • 4

1 Answers1

1

You can use the tzinfo gem to navigate through different timezones and it supports DST. The Whenever gem makes it easy to write your cron jobs in Ruby. I assume your User model has a timezone column which follows The Time Zone Database naming.

So, your schedule.rb would be something like this:

require "tzinfo"

def midnight_in_timezone(timezone)
  # assumes your server runs in utc         
  TZInfo::Timezone.get(timezone.name).local_to_utc(Time.parse('00:00am')).strftime('%H:%M%p')
end

set :output, "/var/log/cron_log.log"

TZInfo::Timezone.all.each do |timezone|
  every :day, :at => midnight_in_timezone(timezone) do
    # pass in timezone so you can perform your task
    # for users who match => User.where(timezone: timezone)
    runner "SomeModel.run_your_midnight_task('#{timezone}')"
  end
end
Gyt Dau
  • 35
  • 4
Petr Gazarov
  • 3,602
  • 2
  • 20
  • 37