10.4. Using Cron, Anacron, and One-Time Jobs
cron predates systemd by decades and remains everywhere: it is
minute-granular, per-user, and so simple that its failure modes are
famous. anacron layers day-granular catch-up on top for machines that
are not always running, and at handles the one-shot "run this
later". The mechanisms divide the work like this:
| Mechanism | Resolution | After downtime | Run records | Fits |
|---|---|---|---|---|
| systemd timer | seconds to calendar dates | one catch-up run with Persistent=true |
journal, per service | services needing limits, dependencies, randomized delays |
| cron | one minute | missed runs stay missed | job output mailed; session lines in journal | traditional minute jobs, per-user schedules |
| anacron | one day | runs once per period after startup | as cron (it runs the jobs) | daily and weekly maintenance on intermittently off machines |
| at | once, at a named time | not applicable - a single deferred command | output mailed | one-time deferred commands |
The examples run on clock, as john unless a block shows sudo. The
cron package and its cron.service are part of a standard
installation. Cron's mail-based failure reporting needs a local mail
transport, so the exercises use the packaged Exim; install
exim4-daemon-light with bsd-mailx if they are not present, and
choose "local delivery only" at the Exim configuration prompt -
nothing here leaves the machine.
10.4.1. User Crontabs and System Cron Directories
cron reads schedules from two kinds of places: per-user crontabs,
installed with the crontab command and stored under
/var/spool/cron/crontabs, and system files under /etc:
| Location | Who it schedules | Managed by |
|---|---|---|
| per-user crontab spool | The user who runs crontab |
crontab file, crontab -l, crontab -r, crontab -e |
/etc/crontab |
System jobs (has a user field) | administrator, by hand |
/etc/cron.d/* |
System jobs (has a user field) | administrator, by hand; also how packages ship schedules |
/etc/cron.hourly, .daily, .weekly, .monthly, .yearly |
Scripts run by the /etc/crontab and anacron entries |
drop a script into the directory |
A crontab line is five time fields - minute, hour, day-of-month,
month, day-of-week - followed by the command; the system files add a
user field between them. Build a user crontab that demonstrates the
environment cron provides. The job script first, cron-heartbeat.sh:
#!/bin/bash
printf '%s PATH=%s\n' "$(date -u +%FT%TZ)" "$PATH" >> /home/john/debian-handbook/timekeeping/cron-runs.log
echo "cron-heartbeat stdout"
echo "cron-heartbeat stderr" >&2
It logs the PATH cron gave it and deliberately writes to both
standard output and standard error - the two streams cron's mail
notification is built on. The crontab source file,
john-crontab.txt:
SHELL=/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin
MAILTO=john
* * * * * /home/john/debian-handbook/timekeeping/cron-heartbeat.sh
Beyond the schedule line, three assignments matter: SHELL=/bin/bash,
because cron's default shell is /bin/sh regardless of the user's
login shell; PATH=, because cron's default PATH is minimal and
jobs fail mysteriously without it; and MAILTO=john - cron mails the
job's combined output to this local user (an empty MAILTO= suppresses
the mail entirely). Install it as john's crontab:
$ crontab john-crontab.txt
Silent - the file is parsed, stored in the spool under john's name, and installed. List it back:
$ crontab -l
SHELL=/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin
MAILTO=john
* * * * * /home/john/debian-handbook/timekeeping/cron-heartbeat.sh
Wait for the next minute boundary, then read what the job recorded:
$ cat cron-runs.log
2026-11-19T23:58:01Z PATH=/usr/local/bin:/usr/bin:/bin
The job ran at 23:58:01 - cron starts jobs at the top of the minute,
and the second is launch latency - with exactly the PATH the
crontab set. The paired notification arrived as local mail:
$ cat /var/mail/john
From john@clock Thu Nov 19 23:58:10 2026
Return-path: <john@clock>
Envelope-to: john@clock
Delivery-date: Thu, 19 Nov 2026 23:58:10 +0000
Received: from john by clock with local (Exim 4.98.2)
(envelope-from <john@clock>)
id 1xUC0z-000000008UV-3XOD
for john@clock;
Thu, 19 Nov 2026 23:58:06 +0000
From: root@clock (Cron Daemon)
To: john@clock
Subject: Cron <john@clock> /home/john/debian-handbook/timekeeping/cron-heartbeat.sh
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: quoted-printable
X-Cron-Env: <SHELL=/bin/bash>
X-Cron-Env: <PATH=/usr/local/bin:/usr/bin:/bin>
X-Cron-Env: <MAILTO=john>
X-Cron-Env: <HOME=/home/john>
X-Cron-Env: <LOGNAME=john>
Message-Id: <E1xUC0z-000000008UV-3XOD@clock>
Date: Thu, 19 Nov 2026 23:58:05 +0000
cron-heartbeat stdout
cron-heartbeat stderr
The file holds the message cron delivered; on a system with other
local mail, earlier messages precede it. Read the header: cron
constructs the message with From: root@<host> (Cron Daemon), the
subject is the job's command line, and the X-Cron-Env lines record
the exact environment the job ran under - the same PATH the job
logged, plus HOME and LOGNAME. Both the stdout and the stderr
lines are in the body: cron merges the two streams into one message.
That message is the entire failure mechanism, and its consequences are
Section 10.4.2's subject. The scheduler's own view:
$ sudo journalctl -u cron --no-pager -n 8
Nov 19 23:58:01 clock CRON[32639]: pam_unix(cron:session): session opened for user john(uid=1001) by john(uid=0)
Nov 19 23:58:01 clock CRON[32641]: (john) CMD (/home/john/debian-handbook/timekeeping/cron-heartbeat.sh)
Nov 19 23:58:06 clock CRON[32639]: pam_unix(cron:session): session closed for user john
Nov 19 23:59:01 clock CRON[32740]: pam_unix(cron:session): session opened for user john(uid=1001) by john(uid=0)
Nov 19 23:59:01 clock CRON[32742]: (john) CMD (/home/john/debian-handbook/timekeeping/cron-heartbeat.sh)
The CMD lines name each job as it started, with a PAM session opened
and closed around each. Two runs are visible - the job has kept
running every minute since installation. Remove the crontab and
confirm:
$ crontab -r
$ crontab -l
no crontab for john
crontab -r is silent; -l now reports on stderr that no crontab
exists. (crontab -e edits the crontab in $EDITOR interactively -
the file-plus-crontab file flow used here produces the same content
by a reviewable path.)
crontab form |
Description |
|---|---|
crontab FILE |
Install FILE as your crontab, replacing any existing one. |
crontab -l |
List your crontab. |
crontab -r |
Remove your crontab. |
crontab -e |
Edit your crontab in $EDITOR. |
The system side, /etc/cron.d, is where an administrator schedules
work without a per-user crontab. The script, maintenance.sh - it
writes to a state directory that must exist before the job first runs:
#!/bin/sh
printf '%s system-cron\n' "$(date -u +%FT%TZ)" >> /var/lib/handbook-cron/maintenance.log
The schedule file, handbook-maintenance.cron - note the root user
field after the five time fields, and the environment lines:
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
* * * * * root /usr/local/lib/handbook/maintenance.sh
Install the script and the schedule file, and create the state directory the script writes to - all owned by root:
$ sudo install -d -m 755 /usr/local/lib/handbook
$ sudo install -m 755 maintenance.sh /usr/local/lib/handbook/maintenance.sh
$ sudo install -m 644 handbook-maintenance.cron /etc/cron.d/handbook-maintenance
$ sudo install -d -m 755 /var/lib/handbook-cron
All silent. Check the file cron actually sees:
$ ls -l /etc/cron.d/handbook-maintenance
-rw-r--r-- 1 root root 134 Nov 19 23:59 /etc/cron.d/handbook-maintenance
cron requires /etc/cron.d files to be owned by root and writable by
no one else - mode 644 here - and ignores files whose names contain a
dot; handbook-maintenance obeys both rules. cron picks the file up
without any reload. After the next minute:
$ cat /var/lib/handbook-cron/maintenance.log
2026-11-20T00:00:01Z system-cron
$ sudo journalctl -u cron --no-pager -n 5
Nov 19 23:59:01 clock CRON[32742]: (john) CMD (/home/john/debian-handbook/timekeeping/cron-heartbeat.sh)
Nov 19 23:59:05 clock CRON[32740]: pam_unix(cron:session): session closed for user john
Nov 20 00:00:01 clock CRON[32993]: pam_unix(cron:session): session opened for user root(uid=0) by root(uid=0)
Nov 20 00:00:01 clock CRON[32995]: (root) CMD (/usr/local/lib/handbook/maintenance.sh)
Nov 20 00:00:01 clock CRON[32993]: pam_unix(cron:session): session closed for user root
The journal shows the same flow as before, with (root) where the
user crontab showed (john). Remove the schedule file when done -
cron stops scheduling it immediately:
$ sudo rm -f /etc/cron.d/handbook-maintenance
Silent; the script and the state directory are part of the chapter's closing cleanup.
10.4.2. Environment, Locking, Output, and Failure Notifications
The mail in Section 10.4.1 demonstrated cron's whole notification model, and its blind spot deserves its own figure. cron mails the job's output - nothing more:
Figure 10.4. Conceptual comparison of the failure paths. cron's only report is the job's own output delivered by mail; a systemd timer can route failures to a dedicated alert unit that runs whatever handling the administrator defines.
The consequences, in the order they bite:
- A job that exits nonzero but prints nothing sends no mail at all -
cron does not add a failure report of its own. Have failing jobs say
so:
echo "backup failed: $reason" >&2makes the failure visible; a bareexit 1is silent. - The minimal environment cuts both ways: the
PATHandSHELLlines in the mail headers exist because cron runs jobs in a nearly empty environment - no profile, no login shell. The capturedPATHvalue is the whole story: anything not on it must be called by absolute path. - Output is the signal, so a chatty job mails every minute forever.
Redirect deliberate output to a file (
>> log 2>&1) and print only what warrants a message; Chapter 8'sloggeris the alternative that lands in the journal instead of a mailbox.
A second classic problem is overlap: an every-minute job whose
previous run is still going. systemd timers serialize by design
(Section 10.3.3); cron does not - it happily starts a second copy. The
standard guard is flock, which holds an advisory lock file for the
duration of a command. The job, locked-job.sh:
#!/bin/bash
printf '%s locked-job\n' "$(date -u +%FT%TZ)" >> /home/john/debian-handbook/timekeeping/locked-runs.log
flock option |
Description |
|---|---|
-n |
Do not wait: if the lock is held, fail immediately with exit status 1. |
-c "command" |
Run the command under the lock held on the file. |
The demonstration holds the lock for eight seconds in the background and tries to run the job under the same lock twice - once while the lock is held, once after the holder exits:
$ flock lockfile -c "sleep 8" &
holder=$!
sleep 1
flock -n lockfile ./locked-job.sh
echo first=$?
wait $holder
flock -n lockfile ./locked-job.sh
echo second=$?
cat locked-runs.log
first=1
second=0
2026-11-20T00:00:19Z locked-job
The bounded sequence works like this: the first line starts an
eight-second lock holder in the background and stores its job ID in
holder; sleep 1 lets the lock be taken; the first flock -n finds
the lock held, refuses to wait, and runs nothing - echo first=$?
reports the exit status 1; wait $holder blocks until the holder
finishes, releasing the lock; the second flock -n acquires it and
runs the job, reporting 0. Only the second attempt wrote to the log.
In a crontab the same guard is one line -
flock -n /run/lock/handbook-job.lock /usr/local/lib/handbook/job.sh
- and a locked-out run simply ends with status 1, sending no mail if
the script printed nothing on that path. /run/lock is the
conventional home for lock files of running-system jobs.
10.4.3. Anacron on Systems That Are Not Always Running
cron's minute grid assumes the machine is on. anacron makes a
different assumption: jobs are daily-or-coarser, and the machine may
have been off at the scheduled time. Each job has a period in days and
a stamp file under /var/spool/anacron recording the date it last
ran; when anacron starts and finds the stamp older than the period,
the job runs once, then the stamp is updated. Debian runs anacron from
a systemd timer, and its packaged configuration drives the
/etc/cron.daily and sibling directories from Section 10.4.1's
table - that is how daily maintenance happens on a machine that boots
at noon.
anacron has no per-user crontab equivalent: the packaged setup runs it
as root from one file, /etc/anacrontab. Its job lines are four
fields - period in days, delay in minutes after anacron starts, a job
identifier that names the stamp file, and the command - with the same
environment-assignment syntax as crontabs. First the practice job's
script, as john in the workspace on clock - saved as anacron-job.sh:
#!/bin/bash
date -u +%FT%TZ >> /home/john/debian-handbook/timekeeping/anacron-runs.log
Then keep a backup of the packaged file and install a practice copy that adds one line to it:
$ sudo cp /etc/anacrontab /etc/anacrontab.backup
The backup copy prints nothing. The practice /etc/anacrontab - the
packaged environment and job lines (comments dropped) plus the new last
line, with period 1 day and delay 0 so
the demonstration runs immediately (the packaged entries use delays of
5–20 minutes to stagger work after boot). Save this as
~/debian-handbook/timekeeping/anacrontab:
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
HOME=/root
LOGNAME=root
1 5 cron.daily run-parts --report /etc/cron.daily
7 10 cron.weekly run-parts --report /etc/cron.weekly
@monthly 15 cron.monthly run-parts --report /etc/cron.monthly
@yearly 20 cron.yearly run-parts --report /etc/cron.yearly
1 0 handbook-time /home/john/debian-handbook/timekeeping/anacron-job.sh
Install it and validate the syntax:
$ sudo install -m 644 anacrontab /etc/anacrontab
$ sudo anacron -T
anacron option |
Description |
|---|---|
-T |
Validate /etc/anacrontab syntax; prints nothing when valid. |
-u JOB |
Update JOB's stamp to today without running it. |
-d |
Run in the foreground with progress messages on stderr. |
-f |
Force runs regardless of stamps. |
-n |
Run jobs without their delay; also implies serialized execution. |
Both commands are silent. Now the full lifecycle. The remaining
anacron work is root's - enter a root shell on clock (sudo -i from
john's shell; leave it with exit) and mark the job as if it ran
today, then run anacron for it:
# anacron -u handbook-time
# anacron -d handbook-time
Anacron 2.3 started on 2026-11-20
Normal exit (0 jobs run)
-u updated the stamp silently, so -d found nothing due and ran
zero jobs - the not-due path. Delete the stamp - the removal prints
nothing - to imitate a machine that was off yesterday, and run again:
# rm -f /var/spool/anacron/handbook-time
# anacron -d handbook-time
Anacron 2.3 started on 2026-11-20
Will run job `handbook-time' in 0 min.
Job `handbook-time' started
Job `handbook-time' terminated
Normal exit (1 job run)
One job ran. Read the evidence it left - as john, back in the ordinary
shell after exit; the script ran as root, so the log file it created
is root-owned but world-readable:
$ cat anacron-runs.log
2026-11-20T00:00:27Z
Force a run regardless of the stamp, with the delay suppressed - the combination a manual "run the daily jobs now" needs. In the root shell again:
# anacron -f -n -d handbook-time
Anacron 2.3 started on 2026-11-20
Will run job `handbook-time'
Jobs will be executed sequentially
Job `handbook-time' started
Job `handbook-time' terminated
Normal exit (1 job run)
Two differences from the previous run: no "in 0 min", because -n
removed the delay, and the explicit sequential-execution notice -
-n implies serialized runs, which anacron announces. The stamp it
maintains:
# ls -l /var/spool/anacron/handbook-time
-rw------- 1 root root 9 Nov 20 00:00 /var/spool/anacron/handbook-time
Nine bytes - the date string. The packaged trigger that makes this happen on real systems is itself a systemd timer with the Section 10.3 vocabulary:
# systemctl cat anacron.timer
# /usr/lib/systemd/system/anacron.timer
[Unit]
Description=Trigger anacron every hour
[Timer]
OnCalendar=*-*-* 07..23:30
RandomizedDelaySec=5m
Persistent=true
[Install]
WantedBy=timers.target
Half past each hour between 07:00 and 23:00, delayed randomly by up to five minutes, persistent across downtime. The catch-up is the same stamp-backed mechanism Section 10.3.3 demonstrated: a laptop opened at 10:14, having missed the morning elapses, gets its first anacron pass within a few minutes of boot - subject to the randomized delay - not at the next half hour, and the daily jobs' stamps decide what actually runs. Restore the packaged file and remove the practice stamp, still in the root shell:
# mv /etc/anacrontab.backup /etc/anacrontab
# rm -f /var/spool/anacron/handbook-time
# exit
All three silent; the backup replaces the practice copy and the stamp disappears.
10.4.4. Scheduling and Removing at Jobs
at defers a single command to a named later time - the tool for
"run this report tonight at 02:00" without writing a crontab line to
delete afterwards. Its daemon atd is active on a standard system,
checked as john:
$ systemctl is-active atd
active
The job script, at-job.sh:
#!/bin/bash
date -u +%FT%TZ >> /home/john/debian-handbook/timekeeping/at-runs.log
Queue it by feeding the command to at on standard input, with the
time in the natural "now + …" form:
$ echo /home/john/debian-handbook/timekeeping/at-job.sh | at now + 1 minute
warning: commands will be executed using /bin/sh
job 14 at Fri Nov 20 00:01:00 2026
The warning is a reminder that at runs its commands with /bin/sh,
not your login shell; the second line gives the job number (14) and
the computed time - the next minute boundary. Submit from a directory
the job can still reach when it runs: at records the submitting
shell's working directory and re-enters it at execution time, so a job
queued from a since-deleted directory fails before its command starts.
The queue, per user:
$ atq
14 Fri Nov 20 00:01:00 2026 a john
One entry: job number, time, queue letter (a is the default at
queue), owner. After the minute passes, the job has run and the queue
is empty:
$ cat at-runs.log
2026-11-20T00:01:00Z
$ atq
The empty atq prints nothing. The removal path, with a job queued
two hours out:
$ echo true | at now + 2 hours
warning: commands will be executed using /bin/sh
job 15 at Fri Nov 20 02:01:00 2026
$ atq
15 Fri Nov 20 02:01:00 2026 a john
$ atrm 15
$ atq
atrm 15 is silent, and the second atq confirms the queue is empty
- the job number is the handle atq printed. The related batch
command queues work to run when system load permits, using the same
queue machinery; its behavior is documented alongside at in at(1).