How to Set Crontab Timezone
If you’ve ever struggled to set the correct timezone for your cron jobs on Ubuntu 22.04, you’re not alone. In this blog, we’ll walk you through a troubleshooting journey that highlights common pitfalls and the ultimate solution.
The Problem: Why Isn’t My Cron Task Running as Expected?
Imagine this scenario: you set up a cron job to run at a specific time, but it doesn’t execute as planned. After some digging, you realize the issue might be related to timezones. You try a few fixes but nothing seems to work.
Step 1: Trying CRON_TZ
Modern cron implementations support the CRON_TZ
variable, which allows you to specify the timezone for individual cron
jobs. Here’s an example for crontab -e
:
CRON_TZ=Asia/Shanghai
0 8 * * * /path/to/your/script.sh
In theory, this should ensure the job runs at 8:00 AM Beijing Time.
However, CRON_TZ
doesn’t work as expected on my Ubuntu
22.04.
Step 2:
Setting the System Timezone with timedatectl
Try setting the system timezone globally using
timedatectl
:
sudo timedatectl set-timezone Asia/Shanghai
This command updates the system timezone, and you can verify it with:
$ timedatectl
Local time: Fri 2024-12-06 20:44:09 CST
Universal time: Fri 2024-12-06 12:44:09 UTC
RTC time: Fri 2024-12-06 12:44:09
Time zone: Asia/Shanghai (CST, +0800)
System clock synchronized: yes
NTP service: active
RTC in local TZ: no
Unfortunately, I found that crontab still doesn't work.
Step 3: The Real Culprit: Restarting the Cron Service
The key step that many people overlook is restarting the
cron
service after making timezone changes. By default,
cron reads the system timezone during startup and doesn’t automatically
refresh it when the system timezone changes.
To fix this, simply restart the cron service:
sudo systemctl restart cron.service
Once restarted, cron will use the updated timezone.
Step-by-Step Guide
To avoid any issues with cron and timezones on Ubuntu 22.04, follow these steps:
Set the Desired Timezone Globally:
sudo timedatectl set-timezone Asia/Shanghai
Verify the Timezone:
timedatectl
Restart the Cron Service:
sudo systemctl restart cron.service