Let's imagine that you need to set default time zone in your Rails app. You go to application.rb
and write:
config.time_zone = 'Central Time (US & Canada)'
As simple as that. Now your app will take into account this info when you will perform some actions based on time.
Now, let's say, you need to add some recurring jobs. Most probably you will use whenever
gem and will have this kind of code in gem generated schedule.rb
:
every :monday, at: '9am' do
rake 'send_weekly_reports'
end
What this code will do? It will run send_weekly_reports
rake task each Monday at 9am. But. 9am at what time zone? Maybe time zone that we previously set as our app default time zone? No. It will use server time zone.
But what if you want to use your app time zone? We have 2 options here:
a) we can change our server time zone to the same time zone as we use in our app;
b) we can handle it inside our app.
Let's see how you can handle it inside the app.
You will need to add this code to your schedule.rb
file:
require_relative './environment'
def timezoned time
Time.zone.parse(time).utc
end
every :monday, at: timezoned('9am') do
rake 'send_weekly_reports'
end
Now you will need to use method timezoned
by passing required time to it and get your time parsed to UTC which is mostly used by servers.
require_relative './environment'
is here to be able to call timezoned
method code.
As a result, now if we are setting some job to be run at 9am, it will run at 9am at the time zone defined by you at application.rb
.
Cover image by Stanley Dai on Unsplash
Top comments (0)