czwartek, marca 24, 2011

Timezone aware cron usage

If your whole application environment is working within one particular timezone, then you are a happy man. Sometimes, especially when you are performing synchronizations with partners from different timezones, and those timezones are changing their time basing on the DST rules. This might be a nightmare, when your scheduled task change their execution time back and forth by one hour every time they want. Simply saying: you may adjust those time manually, it is doable, but please, do you want to do this up to four times a year? What a horrible loss of time!
There are two approaches nice and hard, which one is applicable for you? It depends on the cron compilation configuration. Check it by calling:

man 5 crontab
in console. Of course, you know how to configure cron, scroll down up to example, and when you see something like this:

# mail any output to `paul', no matter whose crontab this is MAILTO=paul # CRON_TZ=Japan # run five minutes after midnight, every day 5 0 * * *       $HOME/bin/daily.job >> $HOME/tmp/out 2>&1 # run at 2:15pm on the first of every month -- output mailed to paul 15 14 1 * * $HOME/bin/monthly
Your way is the easy way, change CRON_TZ variable to desired timezone (in which next command will be executed). Timezone may be changed many times inside of one crontab, default timezone is this one from server.

When you are out of luck, and you don't see that crontab supports CRON_TZ  you will have to write your own mini script, which will perform checking not implemented in cron. First, specify desired timezone for your script:

TZ=Japan 0 4,5,6,7 * * *       ~/japan_cron.sh
Determine what are the highest, and the lowest possible differences between server timezone and desired timezone - when each timezone can change time by one hour, maximum difference is two hours, this results in four hour window in which script should be executed.
The last thing which we have to create is the cron script which will be executed at desired hours and will check current time against desired execution time (hard to explain, example next):

#!/bin/bash #0900 if [ `date +'%H%M'` = '0900' ] then         php nine_am_sync.php fi
Script will check time (in desired timezone) and do what it has to be done. This is not very sophisticated, but simple and working solution.

Brak komentarzy:

Publikowanie komentarza