Abstract
- Cron jobs are tasks scheduled to run automatically at specific times or intervals
Every N units
*/5 * * * *
: Runs the job every 5 minutes.
0 */5 * * *
: Runs the job every 5 hours.
0 0 */5 * *
: Runs the job every 5 days.
Systemd Timers
Systemd Timers are the modern alternative to Cron jobs.
Set cron job with interactive visual
Crontab
crontab
is used on Unix-like systems to manage Cron Job
Code
You can set a cron job using
crontab -e
and view cron jobs usingcrontab -l
.
Cron Job not triggered?
Make sure always specify the absolute path of the command. Cron job has a limited
PATH
environment variable.
Cronitor
- By default, we aren’t alerted when a Crontab fails. We can use a 3rd party tools like Cronitor to get notified via emails when the cron job fails. Cronitor provides great visibility into the cron job by installing an agent alongside the cron job, so we are able to obtain error logs of cron jobs too!
- You can also look into Healthchecks.io or uptime-kuma if you want a self-hosting option
Cron Job and Environment Variables
- Cron job runs with minimal environment variables compared to the commands/scripts you run in the terminal
Why is it so?
When we run commands/scripts in terminal, we also load shell profiles like
.bashrc
and.profile
with all the custom variables.For cron
env
, no shell initialisation files are loaded.
Important
Cron jobs are executed under the user profile that sets them. The script runs from the user’s
$HOME
Set Environment Variables in Cron Job
# Set PATH in crontab
PATH=/usr/local/bin:/usr/bin:/bin
0 2 * * * script.sh
# Use absolute paths
0 2 * * * /usr/local/bin/python3 /home/user/script.py
# Debugging script (env, $HOME)
* * * * * env > /tmp/cronenv.txt && echo "\nHome directory: $HOME" >> /tmp/cronenv.txt && echo "\nThe directory cron job running from: $(pwd)" >> /tmp/cronenv.txt