Tweaking into whenever gem timezone

Rishi Pithadiya
2 min readSep 13, 2019

--

Credits: Google Images

whenever gem is used when there’s need of run specific job at particular intervals, say -

  • send invoices
  • send daily reports
  • send reminder notifications etc..

Once you setup whenever, it will create a schedule.rb file under config directory. You can edit it to schedule particular task.

Suppose we need to send daily sales reports at 9:00 AM every day:

Checkout other options for schedule a job

The problem in above code is timezone for local environment might be different from timezone of server where application is deployed.

Let’s check local and server timezones -

Local timezone

$> Time.now.getlocal.zone
“IST”

Server timezone

$> Time.now.getlocal.zone
“UTC”

So the code written would be executed at 2:30 PM and not at 9:00 AM. To solve it we need to modify following line from

every 1.day, at: ‘9:00 am’ do

to

every 1.day, at: ‘3:30 am’ do

It’ll solves our issue partially.

Now, consider a scenario where we need to run our cron at 10:00 AM to 7:00 PM indian standard timings(IST). We need to add following code to our schedule.rb file -

Run cron in 10:00 AM to 7 PM in Indian Standard Time(IST)

Unfortunately, it becomes more complicated as every-time we need to convert hours to UTC to add it in our schedule.rb file 😖

Now, to solve this we can do one thing, we can convert local time to UTC using following method -

ActiveSupport::TimeZone.new(‘Mumbai’).local_to_utc(Time.parse(‘9:00 am’)).strftime(‘%l:%M %P’).strip"3:30 am"

It’ll convert local time to UTC time(used by server). We can create a separate method in schedule.rb file which include above statement.

Actual Tweaking in Schedule.rb file => to_utc(*time) method

Now, your code become more readable as to_utc method is available for converting IST time to UTC server time 🤟🏼

Setting application timezone should be part of whenever gem. It’s not available as of now and there’s open issue also available on it’s github repository -

Can whenever take timezone from config? #662 🛠

I hope it might available in near future 🤞🏼

References -

Found this post useful? please click the 👏 button and share to help others find it! Feel free to leave a comment below.

--

--

Rishi Pithadiya

Finding happiness in words, food, places & untold stories ✌🏼 rishi.tips