Cron and scheduled tasks — running something automatically
Any task you'd otherwise have to remember to run yourself — a nightly backup, a cleanup script, a health check every five minutes — is a job for cron, the scheduler almost every Linux system already has running.
Beginner
2 min read
The problem cron solves
Some scripts need to run themselves on a schedule, not whenever a person
remembers to. cron is the standard Linux scheduler for exactly this —
a background service (crond) checks a schedule once a minute and runs
anything due, whether or not anyone is logged in.
Reading a crontab entry
Each user has their own schedule, called a crontab, edited with:
$ crontab -e
Every line follows the same five-field format, then the command to run:
A * means "every value" for that field. So 0 3 * * * reads as "at minute
0 of hour 3, every day of every month, every day of the week" — i.e., every
day at 3:00 AM. A few common patterns:
0 3 * * * # every day at 3:00 AM*/15 * * * * # every 15 minutes0 9 * * 1 # every Monday at 9:00 AM (1 = Monday)0 0 1 * * # midnight on the 1st of every month
Where cron's output actually goes
A cron job has no terminal attached, so its output isn't shown anywhere you'd
normally look. By default cron tries to email any output to the job's
owner — which on most modern systems means an unread local mailbox, or
nothing at all because no mail service is set up. Two things worth doing in
every real cron job because of this:
Redirect output to a log file, or you'll most likely have no record
you'll ever see of what happened or whether it failed:
(>> appends rather than overwriting; 2>&1 redirects errors into the
same log — both covered in the redirection and pipes lesson.)
Use absolute paths for everything inside the script — cron jobs run
with a minimal environment, without the same PATH and shell config your
interactive terminal has, so a script that works fine when you run it
manually can fail silently under cron for reasons that only show up once
you check the log.
Why this matters day to day
Cron is the quiet, unglamorous mechanism behind an enormous share of routine
infrastructure work — log rotation, database backups, certificate renewal,
periodic health checks — running reliably in the background without anyone
having to remember to trigger it. Being able to read an existing crontab
entry on sight, and knowing to check the log file first when a scheduled job
"didn't run," are both genuinely common, practical skills once you're
responsible for anything running in production.