Advanced Cron Techniques: Environment, Locking, and Error Handling
Cron basics are easy. The problems are the minimal environment, missing locks, and silent failures. Here is how I make scheduled jobs dependable. Cron is reliable for running tasks on a schedule, but the basics only get you so far. The problems that bite people are not the schedule syntax but the environment cron runs in, the lack of locking, and silent failures. After debugging many cron jobs that worked when run manually but failed under cron, here are the techniques I use to make scheduled jobs dependable. The Environment Problem Cron runs jobs with a minimal environment, not your interactive shell profile. Paths are different, variables you set in bashrc are absent, and commands installed in non-standard locations are not found. This is the number one reason a job works when you run it but fails under cron. # Inside a cron job, set PATH explicitly PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin 0 2 * * * /opt/scripts/backup.sh I set PATH at the top of the crontab, and I also source any environment file the script needs inside the script itself. I never assume a variable is set just because it is in my shell. #!/usr/bin/env bash…