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:
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:
| |
This command updates the system timezone, and you can verify it with:
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:
| |
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: