A backup script is only useful if it runs every night, including the nights you forget. Linux has two schedulers you will meet in every job: cron, the classic one that has run on Unix systems for decades, and systemd timers, the modern alternative built into systemd. This lesson shows how to use both, and the handful of traps that make scheduled scripts fail silently.
In simple words
- cron: the classic Linux scheduler that runs commands at set times.
- Crontab: your list of scheduled jobs, with five time fields (minute, hour, day, month, weekday) and a command.
- systemd timer: the modern way to schedule jobs, with logs, status and catch-up for missed runs.
- Overlapping runs: a new run starting before the last one finished. Prevent it with a lock.
cron in one picture
The cron daemon wakes up every minute, reads schedule tables called crontabs, and runs any command whose time has come. Each user has their own crontab, and there are system-wide ones in /etc/crontab and /etc/cron.d/.
Look at your crontab:
crontab -l0 2 * * * /opt/scripts/backup.sh >> /var/log/backup.log 2>&1Edit it with crontab -e (it opens your editor and installs the file when you save). Never edit the files under /var/spool/cron by hand.
The five time fields
┌───────────── 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)│ │ │ │ │0 2 * * * /opt/scripts/backup.sh| Syntax | Meaning | Example |
|---|---|---|
* | every value | * * * * * every minute |
n | exactly n | 30 6 * * * at 06:30 |
a,b | a list | 0 9,17 * * * at 09:00 and 17:00 |
a-b | a range | 0 9 * * 1-5 weekdays at 09:00 |
*/n | every n | */15 * * * * every 15 minutes |
More examples worth memorising:
*/5 * * * * every 5 minutes0 * * * * every hour, on the hour15 3 * * 0 Sundays at 03:150 0 1 * * midnight on the 1st of every month0 8-18/2 * * 1-5 every 2 hours from 08:00 to 18:00 on weekdays@reboot once, when the machine starts@daily same as 0 0 * * *Times are in the server's time zone, which on cloud servers is usually UTC. A job set for 0 9 * * * on a UTC server runs at 14:30 in India.
The environment cron gives you is tiny
This is the number one reason "it works when I run it, but not from cron". cron starts your command with:
- a minimal
PATH, typically just/usr/bin:/bin, - no terminal, so nothing can prompt for input,
- your home directory as the working folder,
- none of the variables from your
.bashrcor.profile, /bin/shas the shell for the crontab line itself.
So a script that calls aws, kubectl or docker (installed in /usr/local/bin) fails with "command not found", and you never see the error because nobody is watching. The fixes:
# 1. Set PATH and other variables at the top of the crontabPATH=/usr/local/bin:/usr/bin:/binMAILTO=""SHELL=/bin/bash# 2. Use absolute paths for the script, and cd inside the script if needed0 2 * * * /opt/scripts/backup.sh >> /var/log/backup.log 2>&1Inside the script, set what it needs rather than assuming:
#!/usr/bin/env bashset -euo pipefailexport PATH=/usr/local/bin:/usr/bin:/bincd "$(dirname "$0")" # run relative to the script's own folderAlways capture output
By default cron tries to email output to the user, which on most servers goes nowhere. Redirect everything to a log, with a timestamp from inside the script:
0 2 * * * /opt/scripts/backup.sh >> /var/log/backup.log 2>&1Or send it to the system journal with logger, tagged so you can find it:
0 2 * * * /opt/scripts/backup.sh 2>&1 | logger -t backuplogger -t backup "backup finished: 3 files"tail -n 1 /var/log/syslogNov 29 09:42:01 lab backup: backup finished: 3 filesNote that % is special in crontab lines (it means newline). Escape it as \% when you use date +%F directly in a crontab, or, better, keep such logic inside the script.
Preventing overlapping runs
If a job takes longer than its interval, a second copy starts before the first finishes. Two backups writing the same file, or two deploy jobs at once, cause real damage. Wrap the command with flock:
*/10 * * * * flock -n /tmp/sync.lock /opt/scripts/sync.sh >> /var/log/sync.log 2>&1-n means "if the lock is already held, give up immediately". The lock is released when the script exits, even if it crashes.
systemd timers
On modern Linux distributions, systemd can schedule jobs too. A timer is two small unit files:
- a service unit that says what to run,
- a timer unit with the same name that says when.
systemctl cat backup.servicesystemctl cat backup.timer# /etc/systemd/system/backup.service[Unit]Description=Nightly backup[Service]Type=oneshotExecStart=/opt/scripts/backup.shUser=backup# /etc/systemd/system/backup.timer[Unit]Description=Run backup daily[Timer]OnCalendar=*-*-* 02:00:00Persistent=trueRandomizedDelaySec=5m[Install]WantedBy=timers.targetType=oneshotmeans the service runs to completion and exits, which is what a script does.OnCalendar=is the schedule. Examples:daily,hourly,Mon..Fri 09:00,*-*-* *:00/15:00(every 15 minutes). Check one withsystemd-analyze calendar "Mon..Fri 09:00".Persistent=trueruns a missed job at the next boot, if the machine was off at 02:00. cron simply skips it.RandomizedDelaySec=spreads the start time, so a thousand servers do not hit the backup storage at the same second.
Enable and inspect it:
sudo systemctl daemon-reloadsudo systemctl enable --now backup.timersystemctl list-timersjournalctl -u backup.service -n 4NEXT LEFT LAST PASSED UNIT ACTIVATESMon 2026-11-30 02:00:00 UTC 9h left Sun 2026-11-29 02:00:04 UTC 15h ago backup.timer backup.serviceMon 2026-11-30 06:12:00 UTC 13h left Sun 2026-11-29 06:12:31 UTC 11h ago apt-daily.timer apt-daily.service2 timers listed.Nov 29 02:00:09 lab backup.sh[4121]: [02:00:09] wrote /backup/etc-2026-11-29.tar.gz (12K)Nov 29 02:00:09 lab backup.sh[4121]: [02:00:09] removed 1 backup(s) older than 7 daysNov 29 02:00:09 lab systemd[1]: backup.service: Deactivated successfully.Nov 29 02:00:09 lab systemd[1]: Finished backup.service - Nightly backup.To run the job right now, for testing, start the service directly: sudo systemctl start backup.service.
cron or systemd timer?
| cron | systemd timer | |
|---|---|---|
| Setup | one line | two small files |
| Logs | whatever you redirect | automatic, in the journal |
| Missed runs (machine off) | skipped | Persistent=true catches up |
| Overlapping runs | need flock | never overlaps (the service is already running) |
| Resource limits, sandboxing | no | yes (MemoryMax=, ProtectSystem= …) |
| Dependencies ("after network is up") | no | yes |
| Available in containers / minimal images | often | usually not (no systemd) |
A practical rule: use systemd timers on servers you manage, and cron where systemd is not available or for quick personal jobs. In Kubernetes, neither: use a CronJob resource, which uses the same five-field schedule.
Writing scripts that behave well on a schedule
Scheduled scripts run unattended, so they need all the safety habits from the last lessons, plus a few more:
#!/usr/bin/env bashset -euo pipefailexport PATH=/usr/local/bin:/usr/bin:/bin log() { printf '[%s] %s\n' "$(date '+%F %T')" "$*"; }trap 'log "FAILED at line $LINENO"' ERR exec 9> /var/lock/backup.lockflock -n 9 || { log "already running, skipping"; exit 0; } log "backup starting"# … work …log "backup finished"- Timestamps on every log line, so you can match failures to times.
- A lock, so slow runs never overlap.
- Exit codes that mean something, so monitoring can alert on failure.
- Idempotence: running the job twice should not cause harm. Write to a temp file and rename it into place, instead of writing directly to the final file.
- A heartbeat: for critical jobs, ping a monitoring URL at the end (
curl -fsS https://hc.example.com/ping/backup), and alert when the ping does not arrive. Silence is the most common failure mode of cron jobs.
Real-world scenario: the backup that had not run for three months
A company discovered during an outage that their nightly database backups had stopped three months earlier. The cron job called pg_dump, which a system upgrade had moved to /usr/lib/postgresql/16/bin/. cron's minimal PATH could not find it, the error went to an unread mailbox, and nobody noticed.
The fix had three parts: an explicit PATH in the script, all output sent to the journal with a tag, and a heartbeat ping at the end of a successful run with an alert if no ping arrived in 26 hours. The last one is what really matters: it turns "the job silently stopped" into a page within a day.
Common mistakes
- Relying on your interactive
PATHor variables from.bashrc. - Not redirecting output, so errors vanish.
- Unescaped
%in crontab lines. - Forgetting the time zone of the server.
- Overlapping runs of slow jobs. Use
flock. - Editing a timer and forgetting
systemctl daemon-reload. - No alerting on missed runs: logging failures does not help if the job never starts.
Practice
- Write cron expressions for: every 10 minutes; weekdays at 18:30; every Monday at 07:00; every 6 hours.
- Run
crontab -land explain each field of the line you see. - Use
logger -t practice "hello from bash"and find the line withtail /var/log/syslog. - Read
backup.timerwithsystemctl catand change the schedule (on paper) to run every 15 minutes during working hours on weekdays. - List the timers on the system and find when
backup.servicelast ran.
Cheat sheet
crontab -l / -e list / edit your crontabm h dom mon dow command five fields, then the command*/15 * * * * every 15 minutes0 9 * * 1-5 weekdays 09:00PATH=… SHELL=/bin/bash set at top of crontabcmd >> /var/log/x.log 2>&1 capture outputcmd 2>&1 | logger -t tag send to the journalflock -n /tmp/x.lock cmd never overlap\% escape % in crontabsystemctl list-timers timers and next runsystemctl cat x.timer show a unit filesystemctl enable --now x.timer start schedulingsystemctl start x.service run the job nowjournalctl -u x.service job logsOnCalendar= Persistent=true when / catch up missed runsKey takeaways
- cron runs commands on a five-field schedule; systemd timers pair a service (what) with a timer (when).
- Scheduled jobs get a minimal environment: set
PATH, use absolute paths and never prompt. - Always capture output, add timestamps, and use
flockto prevent overlapping runs. - systemd timers add journald logs, catch-up after downtime and no overlap for free.
- Alert when a job does not run, not only when it fails.