Usually, Cron jobs run using the local time defined in the system. However, you may prefer to run the Cron job in a different timezone without necessarily changing your server’s time and date.
You can check your local time using the timedatectl command as follows:
You can also use the date command as follows:
So, how can you set a different timezone for your Crontabs? Let’s find out.
How to set the timezone for Crontabs
In your local Linux system, timezones are usually specified in the /usr/share/zoneinfo directory. The directory contains a list of continents & countries and their timezones, as shown below.
You can easily adjust the current timezone to a different one using the syntax shown. For example, to set the system to the time in Tokyo, Japan, simply execute:
However, you cannot change your system’s time, especially when multiple users schedule different Cron jobs. This would affect the time their Cron jobs will run.
Thankfully, you can configure a specific timezone for your Cron job as follows:
First, you need to export the TZ variable in your Shell script before any other Shell entries. Next, access your crontab and use the crontab environment variable CRON_TZ at the start of the crontab file.
Suppose I want to set the Cron job to run a backup script at 2:20 pm every day in Europe/London time and not my local time. My local time is 2 hours ahead of London time, so at 2:20 pm in London, my local time will be 4:20 pm or 1420 HRS.
First, head over to the Shell script file and export the TZ variable before any other script entries. Check out what I did in my Shell script.
Save the changes and exit the script.
Next, access your crontab file by running the command:
Make sure to define the crontab variable CRON_TZ before all the other Cron entries as follows.
20 14 * * * /home/james/backup.sh
Save and exit the crontab. To be sure of the settings, you can list the crontab using the command:
So, when the clock ticked 2:20 pm London time, which corresponds to 4:40 pm local time or 1620 HRS, the backup was successful.
This guide is a perfect demonstration that you can actually set a specified timezone for your Crontabs without changing your system time. This way, you can configure different tasks to run in different timezones to suit your needs, for instance, if you want to send emails to subscribers of a certain timezone at their time and not your local time.