Process Management and AutomationLesson 5.3
Scheduling Bash scripts with cron and systemd timers
cron syntax, crontab fields, crontab -e, environment in cron, systemd timer units, OnCalendar syntax, cron vs systemd comparison, logging cron jobs, run-parts, anacron
Cron: Time-Based Job Scheduling
Cron runs commands on a schedule. The syntax is five fields followed by the command.
# Crontab format: min hour day month weekday command
# * means "every"
# Every day at 2:30 AM
30 2 * * * /opt/scripts/backup.sh >> /var/log/backup.log 2>&1
# Every 15 minutes
*/15 * * * * /opt/scripts/health-check.sh
# Weekdays at 8 AM
0 8 * * 1-5 /opt/scripts/send-report.sh
# First day of each month
0 0 1 * * /opt/scripts/monthly-cleanup.shCron runs with a minimal environment โ no PATH to your tools, no HOME-based configs. Always use absolute paths in cron scripts or set PATH at the top of the crontab.
# Top of crontab
PATH=/usr/local/bin:/usr/bin:/bin
SHELL=/bin/bashsystemd Timers (Modern Alternative)
# /etc/systemd/system/backup.timer
[Unit]
Description=Daily backup timer
[Timer]
OnCalendar=*-*-* 02:30:00
Persistent=true # run if missed while system was off
[Install]
WantedBy=timers.targetsystemctl enable --now backup.timer
systemctl list-timers # view all timers and next run timePrefer systemd timers on modern Linux: they survive missed runs (Persistent=true), integrate with journald for logging, and can depend on other services.
