0 / 15 lessons — 0%
Lesson 10 / 15

Cron & scheduled tasks

Backups at 2am, log cleanup every Sunday, a health check every five minutes — cron is the classic way to run something on a schedule without a human triggering it.

crontab -e # edit your personal crontab crontab -l # list what's currently scheduled
# minute hour day-of-month month day-of-week command * * * * * 0 2 * * * /opt/scripts/backup.sh # every day at 2:00 AM */5 * * * * /opt/scripts/healthcheck.sh # every 5 minutes 0 9 * * 1 /opt/scripts/weekly-report.sh # every Monday at 9:00 AM 0 0 1 * * /opt/scripts/monthly-cleanup.sh # midnight on the 1st of every month
FieldRange
minute0-59
hour0-23
day of month1-31
month1-12
day of week0-6 (0 = Sunday)

System-wide jobs (not tied to one user) live in /etc/cron.d/, or the shortcut directories /etc/cron.daily/, /etc/cron.weekly/ — drop an executable script in the right one and it runs on that cadence automatically, no crontab syntax needed.

Cron jobs run with almost no environment set up — no $PATH the way your interactive shell has, no aliases, often a different working directory. A script that works perfectly when you run it by hand can silently fail under cron. Always use full paths to commands and files inside cron scripts, and redirect output somewhere you'll actually see it.
# capture output so a silent failure doesn't stay silent 0 2 * * * /opt/scripts/backup.sh >> /var/log/backup.log 2>&1
Try it yourselfAdd a one-line cron job that runs every minute and appends the date to a file (* * * * * date >> /tmp/cron-test.log), then tail -f /tmp/cron-test.log and watch it fill in real time. Remove it once you've seen it work.