Cron and scheduling
A script that runs only when you remember to run it isn't automation yet. cron runs commands on a schedule: nightly backups, hourly reports, a cleanup every Sunday. It's on every Linux server, and its schedule syntax is reused by GitHub Actions, Kubernetes CronJobs and most cloud schedulers.
The crontab
Each user has a crontab (cron table): a list of schedules and commands.
crontab -l # list your jobs
crontab -e # edit them (opens your editor)
crontab -r # remove ALL your jobs (careful!)Every line has five time fields and then the command:
┌───────────── minute (0–59)
│ ┌─────────── hour (0–23)
│ │ ┌───────── day of month (1–31)
│ │ │ ┌─────── month (1–12 or jan–dec)
│ │ │ │ ┌───── day of week (0–7, 0 and 7 are Sunday, or sun–sat)
│ │ │ │ │
* * * * * command to run| Field value | Meaning |
|---|---|
* |
Every value |
5 |
Exactly 5 |
1,15 |
1 and 15 |
9-17 |
9 to 17 |
*/15 |
Every 15 (0, 15, 30, 45) |
1-5 (day of week) |
Monday to Friday |
Examples
| Schedule | Runs |
|---|---|
*/5 * * * * |
Every 5 minutes |
0 * * * * |
Every hour, on the hour |
30 2 * * * |
Every day at 02:30 |
0 9 * * 1-5 |
09:00 on weekdays |
0 0 1 * * |
Midnight on the 1st of every month |
0 3 * * 0 |
03:00 every Sunday |
0 */6 * * * |
Every 6 hours (00:00, 06:00, 12:00, 18:00) |
@reboot |
Once, when the machine starts |
@daily / @hourly / @weekly |
Shortcuts for 0 0 * * * / 0 * * * * / 0 0 * * 0 |
💡 Can't remember the order? crontab.guru explains any schedule in plain English.
⚠️ If you set both day of month and day of week (
0 0 13 * 5), cron runs when either matches: every 13th and every Friday, not just Friday the 13th.
Installing a job
crontab -e opens an editor. In scripts, install jobs without an editor by piping a new table into crontab -:
service cron start > /dev/null
cat > backup.sh <<'EOF'
#!/usr/bin/env bash
echo "backup ran at $(date -u +%H:%M:%S)" >> /tmp/backup.log
EOF
chmod +x backup.sh
( crontab -l 2>/dev/null; echo "* * * * * $PWD/backup.sh" ) | crontab -
crontab -l* * * * * /home/you/backup.sh
( crontab -l; echo "new line" ) | crontab - keeps the existing jobs and adds one. (Running crontab - with only the new line would replace them all.)
Here's the job running for real, a couple of minutes later:
sleep 125
cat /tmp/backup.log | sed 's/[0-9][0-9]:[0-9][0-9]:/HH:MM:/'backup ran at HH:MM:01 backup ran at HH:MM:01
Cron starts each job right at the beginning of every matching minute. (The sed hides the real hours and minutes.)
Cron's environment is tiny
The #1 cron surprise: "it works in my terminal, but not in cron". Cron runs jobs with almost no environment: a minimal PATH, no ~/.bashrc, your home folder as the working directory, and /bin/sh as the shell.
( crontab -l; echo '* * * * * env | sort > /tmp/cron-env.txt' ) | crontab -
sleep 65
cat /tmp/cron-env.txtHOME=/root LANG=C.UTF-8 LOGNAME=root PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin PWD=/root SHELL=/bin/sh
Notice what's missing: your ~/.bashrc never ran (no aliases, no nvm, pyenv or conda setup), the shell is /bin/sh rather than Bash, and the job starts in the home folder. Ubuntu fills PATH from /etc/environment; on many other systems cron's PATH is just /usr/bin:/bin. Either way, programs in ~/bin, ~/.local/bin or ~/.nvm aren't found. Fixes:
- Use full paths in cron jobs and scripts:
/usr/bin/python3,/home/deploy/app/backup.sh. Find them withcommand -v python3. - Set variables at the top of the crontab; they apply to every job below:
SHELL=/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin
MAILTO=""cdto the right folder inside the script, or use absolute paths for every file it touches.
Capturing output
Cron tries to email anything a job prints, which on most servers goes nowhere. Redirect output to a log file instead:
# m h dom mon dow command
30 2 * * * /home/deploy/bin/backup.sh >> /var/log/backup.log 2>&1Inside the script, timestamp each line so the log is useful:
log() { printf '%s %s\n' "$(date -u '+%Y-%m-%d %H:%M:%S')" "$*"; }
log "backup started"
log "backup finished: 3 files"2026-11-22 09:21:26 backup started 2026-11-22 09:21:26 backup finished: 3 files
Don't let jobs overlap
If a job runs every 5 minutes but sometimes takes 7, two copies run at once and can corrupt each other's work. flock makes sure only one runs:
flock -n /tmp/sync.lock -c 'echo "first copy running"; sleep 2' &
sleep 0.5
flock -n /tmp/sync.lock -c 'echo "second copy running"' || echo "second copy skipped: still locked"
waitfirst copy running second copy skipped: still locked
In a crontab: */5 * * * * flock -n /tmp/sync.lock /home/deploy/bin/sync.sh.
A complete nightly backup job
#!/usr/bin/env bash
# Nightly: archive the app's data folder, keep the last 7 archives.
set -euo pipefail
src=${SRC:-$HOME/app-data}
dest=${DEST:-$HOME/backups}
keep=7
log() { printf '%s %s\n' "$(date -u '+%F %T')" "$*"; }
mkdir -p "$dest"
archive="$dest/app-$(date -u +%Y%m%d-%H%M%S).tar.gz"
tar -czf "$archive" -C "$(dirname "$src")" "$(basename "$src")"
log "created $(basename "$archive") ($(du -h "$archive" | cut -f1))"
# delete all but the newest $keep archives
mapfile -t old < <(ls -1t "$dest"/app-*.tar.gz | tail -n +$(( keep + 1 )))
for f in "${old[@]}"; do
rm -- "$f"
log "deleted old $(basename "$f")"
done
log "done: $(ls -1 "$dest" | wc -l) archive(s) kept"mkdir -p app-data && echo "orders" > app-data/orders.db
mkdir -p backups && for d in 01 02 03 04 05 06 07 08; do touch -d "2025-10-$d" "backups/app-202510$d-020000.tar.gz"; done
bash backup-db.sh | sed -E 's/^[0-9-]+ [0-9:]+/[time]/; s/app-2026[0-9]{4}-[0-9]{6}/app-NEW/'[time] created app-NEW.tar.gz (4.0K) [time] deleted old app-20251002-020000.tar.gz [time] deleted old app-20251001-020000.tar.gz [time] done: 7 archive(s) kept
There were 8 old archives plus the new one; the 2 oldest were deleted. (The sed hides today's date and time.) The crontab line for it:
30 2 * * * flock -n /tmp/backup.lock /home/deploy/bin/backup-db.sh >> /home/deploy/backup.log 2>&1Other ways to schedule
| Tool | When to use it |
|---|---|
| cron | Simple recurring jobs on one server |
| systemd timers | Modern Linux alternative: logs in journalctl, runs missed jobs after downtime (Persistent=true), resource limits. See the Linux track's systemd lesson |
at |
Run something once later: echo "./deploy.sh" | at 23:00 |
sleep / timeout |
Delays and time limits inside scripts: timeout 30 curl … |
| CI schedules | GitHub Actions on: schedule: - cron: '0 3 * * *' (in UTC) |
| Kubernetes CronJob | Scheduled containers in a cluster |
All of them reuse the same five-field cron syntax.
Practice
- Write the cron schedule for: every 10 minutes during working hours (09:00–17:59) on weekdays.
- Add a job that appends the date and the system load (
uptime) to~/load.logevery minute. Check it after 3 minutes, then remove it again. - Wrap a job in
flockso it can't overlap with itself. - Make a cron job that fails (
ls /nope) and capture its error in a log file with2>&1.
1.What does 0 2 * * * mean?
2.A script works in your terminal but fails in cron with "command not found". Most likely cause?
3.Which schedule runs every 15 minutes?
4.How do you stop two copies of a cron job running at the same time?