How can I change the timezone in which a cron job is executed?
I want to change the timezone in which the cron jobs are executed but keep the rest of the system's default timezone. Is this possible?
I read this article https://linuxhint.com/set-timezone-crontab/
but I think this doesn't affect when the job is executed. It just specifies which timezone should be used by the process once launched by cron
Solution 1:
CRON_TZ instructs your cron table to run in the assigned timezone, you can also use TZ, which sets the timezone for your command if you want it to use a timezone different from the system.
# min hour dom month dow command
CRON_TZ=Europe/Helsinki
0 9 * * * TZ=Europe/Helsinki /bin/sh -c 'date +"$USER: \%a \%e \%b \%Y \%H:\%M:\%S \%Z"' >> /tmp/timestamp.log
This cron will run when the clock strikes 09:00 in Finland, i.e., 08:00 here.
[bac0n@betazoid ~ 07:59]: tail -f /tmp/timestamp.log
bac0n: Sat 4 Dec 2021 09:00:01 EET
If you want to run specific scripts in different time zones, you can use systemd.timer
instead. There are endless ways to organize your timer/services, e.g., you can use an instantiated timer to add the different time zones.
# file: [email protected]
[Unit]
Description=Timer for timezone %I
[Timer]
AccuracySec=1s
OnCalendar=*-*-* 09:00:00 %I
[Install]
WantedBy=timers.target
The second service template is a general service for all enabled time zones, there is also possible to create a specific service for a time zone with different sets of properties.
# file: [email protected]
[Unit]
Description=Service for timezone %I
[Service]
Environment=TZ=%I
ExecStart=/bin/date +"%I: %%a %%e %%b %%Y %%H:%%M:%%S %%Z"
StandardOutput=append:/tmp/timestamp.log
Now you can start adding your time zones.
systemctl enable --now 'timezone@Europe\x2fLondon.timer' 'timezone@Europe\x2fStockholm.timer' 'timezone@Europe\x2fHelsinki.timer'