Sub topic 1
Why Scheduled Jobs Fail Without Anyone Noticing
Prerequisites
You should be comfortable with the Linux command line and editing files. You should also know basic shell scripting (variables, exit codes, pipes), how users and file permissions work, and how to read logs.
Why jobs fail silently
A scheduler starts a command at set times. It does not check whether the command worked. A job that exits with an error, hangs, or never starts leaves no trace unless you add one. Common causes include:
- A missing PATH entry, so the command is not found.
- A previous run still going when the next one starts, so two copies write to the same file.
- A machine that was off at the scheduled time, so the run is skipped.
- Output sent to a mail account nobody reads.
Scheduling with cron
Cron reads crontab files. Each line has five time fields (minute, hour, day of month, month, day of week) followed by a command.
# m h dom mon dow command
30 2 * * * /usr/local/bin/backup.shEdit your crontab with crontab -e. Edit root's crontab with sudo crontab -e.
Cron's minimal environment
Cron starts jobs with a small environment. PATH is often only /usr/bin:/bin, so tools in /usr/local/bin or your home directory are not found. Set PATH at the top of the crontab, and send output to a log:
PATH=/usr/local/bin:/usr/bin:/bin
*/15 * * * * /usr/local/bin/sync.sh >> /var/log/sync.log 2>&1Use absolute paths in scripts, and do not assume your shell profile was loaded.
Scheduling with systemd timers
A systemd timer uses two units. The service unit holds the command, and the timer unit holds the schedule.
# /etc/systemd/system/backup.service
[Unit]
Description=Nightly backup
[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh# /etc/systemd/system/backup.timer
[Unit]
Description=Run the nightly backup
[Timer]
OnCalendar=*-*-* 02:30:00
Persistent=true
[Install]
WantedBy=timers.targetEnable the timer with sudo systemctl enable --now backup.timer. Check it with systemctl list-timers backup.timer, and read run output with journalctl -u backup.service.
Exercise
A cron log shows "backup.sh: command not found" for a script in /usr/local/bin. What is the likely cause, and how do you fix it?
Show answer
Cron's PATH does not include /usr/local/bin. Add PATH=/usr/local/bin:/usr/bin:/bin at the top of the crontab, or call the script by its absolute path.