ryoe - The Blog

A blog about nothing

Fun With Time Zones in Rails

Recently, we had a need to limit when certain rake tasks would run. The tasks sync our data with a third party data store that doesn’t change over night for our continental US-based customers. What we wanted is for the tasks to only run between 7am-1am Eastern (4am-10pm Western) which should cover typical waking hours. In other words, we want to ensure the tasks do not run between 1am-7am Eastern.

If you’ve ever worked with time zones before, then you know this is often trickier than you’d expect. This would be no different.

Thankfully, the Ruby Time and Rails ActiveSupport::TimeWithZone classes provide everything we need.

Goal: Do not run certain rake tasks between 1am-7am Eastern

We want an easy way to skip running certain tasks during certain hours of the day. In addtion, we want to be able to define those hours of the day using the time zone of our choice so that it’s easier to understand. Ideally, we’ll be able to write a little helper class so we can do something like this in our rake tasks:

1
2
3
4
5
6
7
8
9
10
11
12
namespace :mydatasync do

  desc 'Syncs the data for syncable things...'
  task sync: :environment do
    unless MyDataSync::RakeTaskTimeHelper.is_allowed_to_run
      # notify team that we're skipping this sync operation
      next
    end

    # sync stuff...
  end
end