Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Linux Task Scheduling: Crontab Syntax, Environment Traps, and systemd Timers

Five fields and almost no environment: why cron jobs fail silently, how percent signs truncate commands, and what systemd timers add.

~4 min readLinux
#Linux#Automation#SysAdmin
3D illustration of five-field crontab clock triggers contrasted with calendar-accurate systemd timer schedulers

Quick Summary

Cron runs a command on a five-field schedule: minute, hour, day of month, month, day of week. crontab -e edits the current user's table, files under /etc/cron.d/ hold system jobs with a user column, and /etc/cron.daily and friends run scripts from a directory. It is simple and it is everywhere, and its two weaknesses are environment and visibility: jobs run with almost no PATH, no shell profile, and their output goes to mail that may not be delivered anywhere.

systemd timers are the modern replacement with the parts cron lacks. A .timer unit schedules a .service unit, so the command, the environment, the user, and the resource limits are all declared in the same place as every other service. Timers support monotonic schedules (OnBootSec, OnUnitActiveSec), calendar schedules with a readable syntax (OnCalendar=Mon..Fri 03:00), Persistent=true for catch-up after downtime, and systemd-analyze calendar to prove what a schedule means.

The practical rule: use cron for a single user's short periodic command where the environment is trivial, and use timers for anything that needs to survive a reboot, log through the journal, run as a different user, or be started with systemctl when it fails.

Basic Syntax & Signature

bash
# User crontab crontab -e # edit crontab -l # list crontab -r # remove (no confirmation) # Format: minute hour day-of-month month day-of-week command # 0-59 0-23 1-31 1-12 0-7 (0 and 7 = Sunday)
cron
# Every 5 minutes */5 * * * * /usr/local/bin/healthcheck.sh >> /var/log/health.log 2>&1 # 03:30 on the first day of every month 30 3 1 * * /usr/local/bin/monthly-report.sh # Weekdays at 09:00 0 9 * * 1-5 /usr/local/bin/digest.sh # Every 2 hours during business hours 0 8-18/2 * * * /usr/local/bin/sync.sh # Named shortcuts @reboot /usr/local/bin/warm-cache.sh @daily /usr/local/bin/rotate.sh @hourly /usr/local/bin/poll.sh # Explicit environment at the top of the file SHELL=/bin/bash PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin MAILTO=ops@example.com CRON_TZ=UTC
bash
# System crontab with a user column: /etc/cron.d/app # minute hour dom month dow user command 0 2 * * * deploy /srv/app/bin/backup.sh >> /var/log/app-backup.log 2>&1

A systemd timer pair:

ini
# /etc/systemd/system/backup.timer [Unit] Description=Nightly backup [Timer] OnCalendar=*-*-* 02:30:00 Persistent=true RandomizedDelaySec=300 [Install] WantedBy=timers.target
ini
# /etc/systemd/system/backup.service [Unit] Description=Backup job [Service] Type=oneshot User=deploy WorkingDirectory=/srv/app EnvironmentFile=/etc/app/backup.env ExecStart=/srv/app/bin/backup.sh

Key Comparison Table

Aspectcronsystemd timer
Schedule syntaxFive fields, crypticOnCalendar=, readable and testable
Command definitionInline in the crontabA separate .service unit
EnvironmentMinimal; must set PATHEnvironment=, EnvironmentFile=
UserThe crontab's owner, or column 6User= in the service
LogsMail, or a redirect you writeJournal, journalctl -u
Missed run while downLostPersistent=true catches up
DependenciesNoneAfter=, Requires=
Resource limitsNoneMemoryMax=, CPUQuota=, Nice=
Random jitterManual sleepRandomizedDelaySec=
ValidationNonesystemd-analyze verify, --test for cron
DiscoveryScattered across users and /etc/cron.dsystemctl list-timers
Sub-minute intervalsNot supportedOnUnitActiveSec=30s

Practical Edge Cases & Deep Dives

1. The job that works by hand and fails in cron

cron
# Fails: python3 is found, but the script's relative imports are not, # and anything installed under ~/.local/bin is missing. 0 3 * * * python3 scripts/report.py
cron
# Fixed: absolute interpreter, absolute script, explicit directory, explicit PATH SHELL=/bin/bash PATH=/usr/local/bin:/usr/bin:/bin 0 3 * * * cd /srv/app && /usr/bin/python3 /srv/app/scripts/report.py >> /var/log/report.log 2>&1

Cron runs commands with sh and a PATH that is usually /usr/bin:/bin. It does not read ~/.bashrc, ~/.profile, or any environment set in an interactive shell. Anything a script needs — virtualenv activation, NODE_ENV, DATABASE_URL — must be in the crontab or sourced by the script itself.

2. Percent signs and the % trap

cron
# Wrong: % terminates the command; everything after it becomes stdin. 0 * * * * date +%Y-%m-%d > /tmp/date.txt # Right: escape every percent sign. 0 * * * * date +\%Y-\%m-\%d > /tmp/date.txt # Or move the command into a script and call the script.

In a crontab, an unescaped % is converted to a newline and the remainder of the line is fed to the command as standard input. This silently truncates date +%F, printf '%s', and any URL with a percent-encoded character.

3. Where the output goes

cron
# Nothing captures the failure: the mail may bounce and be lost. 0 4 * * * /srv/app/bin/reindex.sh # Log it, with timestamps, and keep the file bounded. 0 4 * * * /srv/app/bin/reindex.sh >> /var/log/reindex.log 2>&1 MAILTO=""

Cron mails stdout and stderr to the user's local mailbox when MAILTO is set (the default), and to nobody in particular when no MTA exists. Redirecting to a file with a rotation policy is the reliable option; logger is better still because it lands in the journal next to everything else:

cron
0 4 * * * /srv/app/bin/reindex.sh 2>&1 | logger -t reindex

4. Testing a schedule before trusting it

bash
systemd-analyze calendar 'Mon..Fri 03:00' --iterations=3 systemd-analyze calendar '*-*-* 02:30:00 Asia/Seoul' systemctl list-timers --all systemctl start backup.timer # start the timer now systemctl status backup.timer journalctl -u backup.service -n 50

systemd-analyze calendar prints the next three elapse times, which resolves every argument about whether Mon..Fri includes Friday. For cron, the equivalent sanity check is a one-minute schedule with a date command, run once, rather than reasoning about field order — day-of-month and day-of-week combine with OR, not AND, which surprises almost everyone:

cron
# Runs on the 1st of the month OR on Mondays — not "the first Monday". 0 9 1 * 1 /usr/local/bin/job.sh

5. Overlapping runs

bash
# Cron does not prevent a second instance while the first is still running. # flock makes the job exclusive. */10 * * * * flock -n /var/lock/nightly.lock /srv/app/bin/nightly.sh

A job that normally takes four minutes and occasionally takes twenty will eventually overlap with itself, and the two copies will corrupt each other's output. flock -n exits immediately when the lock is held; without -n it waits, which queues runs instead of dropping them and can build a backlog.

6. Timer that catches up after downtime

ini
[Timer] OnCalendar=*-*-* 02:30:00 Persistent=true AccuracySec=1min

Persistent=true stores the last trigger time in /var/lib/systemd/timers/ and runs the job on boot if the scheduled time passed while the machine was off. Cron has no equivalent: a job scheduled for 02:30 during a 03:00 reboot simply does not run that day. AccuracySec widens the window so systemd can batch the wakeup with other timers, which matters on battery-powered hosts.

bash
# Monotonic: 15 minutes after boot, then every 6 hours # [Timer] # OnBootSec=15min # OnUnitActiveSec=6h

Common Compilation/Runtime Mistakes

SymptomCauseFix
Works manually, fails in cronMinimal PATH and environmentAbsolute paths, explicit PATH
Command truncated at %Unescaped percent in crontabEscape as \%
No output anywhereMail undeliverable, no redirect>> log 2>&1 or logger
Script runs from the wrong directoryNo cd, cron uses $HOMEcd /path && command
Job runs twiceDuplicate entry in two crontabsgrep -r, check /etc/cron.d
Runs at the wrong hourServer timezone differsCRON_TZ or TZ=...
Day-of-month and day-of-week both setFields combine with ORUse one, or guard inside the script
Overlapping executionsSlow job, short intervalflock -n
Timer never firesTimer not enabled, or service failedsystemctl list-timers, status
Timer fires but job failsService environment differs from shellEnvironmentFile=, WorkingDirectory=
Missed run after rebootNo Persistent=trueAdd it to the timer
@reboot does not runCron daemon not started, or non-standard cronUse a systemd WantedBy=multi-user.target service

Scheduling is where a working script becomes an unreliable one, and the failures are almost never in the script. They are in the environment it inherits, the output nobody reads, and the assumption that a schedule means what it looks like. Declaring all three explicitly — environment, logging, and a tested schedule — is the whole difference between cron and a job that can be trusted unattended.

Try matching browser tools

All tools

Small utilities that fit Linux work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Linux guides

More in Linux

All Linux guides

The guides filed next to this one in Linux, in library order.