Chapter 7 · Lesson 8 of 11
Linux for servers

Cron vs systemd timers: which to use for scheduled jobs

Cron runs a command on a time pattern from a crontab line, while a systemd timer activates a service unit on a schedule and adds journal logging, missed-run catch-up and dependency control.

By the end you will

Write a working cron job with logging, build the same job as a systemd service and timer, and choose between them for a given task.

Time
30 min
Level
Intermediate
Check
4 questions
You need
  • An Ubuntu or Debian server you can reach over SSH
  • A user with sudo access

Both cron and systemd timers answer the same need: run something at a set time, such as a backup at 03:00 or a cleanup every hour. The older cron lesson covers the basics. This lesson recaps the syntax, shows where cron jobs go wrong, and builds the same job as a systemd timer so you can choose.

How it works#

Cron is a daemon that wakes every minute, reads crontab files, and starts any command whose time pattern matches. It starts the command in a short-lived shell with a minimal environment and has no memory of runs it missed.

A systemd timer is a unit (name.timer) that activates another unit (name.service) according to a schedule. The service is where the command lives, so you get everything systemd gives a service: its own logs in the journal, User=, resource limits, Environment= and ordering such as After=network-online.target. The service itself is covered in run a service with systemd, and the daemon concept is in the glossary.

Step 1: Cron syntax recap#

Edit your crontab with crontab -e. Each line has five time fields and then the command:

output
# minute hour day-of-month month day-of-week  command
*/15 * * * *   /usr/local/bin/sync.sh
30 3 * * *     /usr/local/bin/backup.sh
0 9 * * 1-5    /usr/local/bin/report.sh
@reboot        /usr/local/bin/on-boot.sh

Fields: minute (0 to 59), hour (0 to 23), day of month, month, day of week (0 to 7, where 0 and 7 are Sunday). * means every, */15 means every 15, 1-5 is a range and 1,3,5 is a list. List jobs with crontab -l. crontab -r removes your whole crontab with no prompt, so avoid it near -e on the keyboard. System jobs go in /etc/cron.d/ and need a username field after the time fields.

Step 2: Cron pitfalls and logging#

Cron uses /bin/sh, a short PATH (often /usr/bin:/bin), no profile files and a home directory only. A job that works by hand can fail with command not found. Fix it three ways:

output
PATH=/usr/local/bin:/usr/bin:/bin
MAILTO=""
30 3 * * * /usr/local/bin/backup.sh >> /var/log/backup.log 2>&1
  • Put PATH= at the top of the crontab, or use absolute paths in every command.
  • Redirect output: >> /var/log/backup.log 2>&1 keeps both stdout and stderr. The redirects are explained in pipes, redirects and xargs. Make sure the log file is writable by the cron user.
  • Escape % as \% in crontab commands, because cron treats a bare % as a newline. This breaks date +%F unless escaped.
  • Cron also reads variables you set at the top, but it does not expand $HOME inside values the way a shell does. See environment variables and the shell profile.

Cron logs the fact that it started a job, not the result. Check with grep CRON /var/log/syslog or journalctl -u cron, which shows (deploy) CMD (...) lines.

Step 3: The same job as a systemd timer#

Create the service. A timer-driven service is usually Type=oneshot, which means it runs, exits and is done:

bash
sudo nano /etc/systemd/system/backup.service
output
[Unit]
Description=Nightly backup

[Service]
Type=oneshot
User=deploy
ExecStart=/usr/local/bin/backup.sh

Create the timer with the same base name:

bash
sudo nano /etc/systemd/system/backup.timer
output
[Unit]
Description=Run backup nightly

[Timer]
OnCalendar=*-*-* 03:30:00
Persistent=true
RandomizedDelaySec=5min

[Install]
WantedBy=timers.target

OnCalendar= takes DayOfWeek Year-Month-Day Hour:Minute:Second. Shortcuts include hourly, daily, weekly, and examples such as Mon..Fri 09:00 or *:0/15 for every 15 minutes. Validate an expression and see when it fires next:

bash
systemd-analyze calendar "Mon..Fri 09:00"

Persistent=true runs the job at boot if the last scheduled time passed while the machine was off. RandomizedDelaySec= spreads load when many machines share the schedule. Activate it:

bash
sudo systemctl daemon-reload
sudo systemctl enable --now backup.timer

Enable the timer, not the service. Run the job on demand with sudo systemctl start backup.service to test it without waiting.

Step 4: Inspect timers and logs#

bash
systemctl list-timers --all
systemctl status backup.timer
systemctl status backup.service
journalctl -u backup.service -n 50

list-timers shows the NEXT, LEFT, LAST and PASSED columns and which unit each timer triggers. The job’s output goes to the journal automatically, with no redirect needed, so you read it as described in read logs with journalctl. A failed run shows Active: failed and the exit code in systemctl status.

Step 5: Choose between them#

Use cron when:

  • The job is a simple command and you want one line in a file.
  • You manage a few hosts by hand, and everyone knows cron.
  • The system has no systemd, such as some minimal containers.

Use a systemd timer when:

  • You need journal logs, per-job user, memory or CPU limits, or After= ordering, for example waiting for the network or a database.
  • A missed run after downtime must still happen (Persistent=true).
  • You want to see status and last run in one place, and block overlapping runs. A timer will not start a service that is still running.
  • You manage the job as a file with a deployment tool.

For containers, schedulers inside the app or a dedicated worker are common, see workers and cron jobs explained.

Check it worked#

bash
systemctl list-timers backup.timer
sudo systemctl start backup.service
journalctl -u backup.service -n 20 --no-pager

You should see the timer with a NEXT time, a service run that exits with status=0/SUCCESS, and your script’s output in the log. For cron, wait for the minute you set, then read the log file you redirected to.

Edge cases and gotchas#

  • Time zones. Cron and timers use the system time zone unless set otherwise. Check timedatectl, and expect a surprise across daylight saving changes.
  • Overlap. Cron starts a second copy if the first is still running. Guard with flock -n /run/backup.lock command. A timer skips while the service is active.
  • Day of month and day of week combine as OR in cron. 0 3 1 * 1 runs on the first of the month and every Monday.
  • User crontab vs system files. /etc/crontab and /etc/cron.d/ have a user column, crontab -e does not.
  • Missing newline. A crontab line must end with a newline, or the last entry may be ignored.
  • Edits need a reload. Editing a .timer or .service file without daemon-reload leaves the old version active.

Troubleshooting#

SymptomLikely causeFix
/bin/sh: 1: node: not found in the cron logShort cron PATHUse full paths or set PATH= in the crontab
Job never runs, no log linesSyntax error, or the cron service is stoppedcrontab -l, then systemctl status cron
bad minute or bad command when saving a crontabInvalid field, or an unescaped %Fix the line and escape % as \%
Failed to enable unit: Unit file backup.timer does not exist.File in the wrong folder or namePut it in /etc/systemd/system/ and run daemon-reload
backup.timer: Unit backup.service not found.Names do not matchGive the .service and .timer the same base name or set Unit=
Timer is active but NEXT shows n/aNo trigger such as OnCalendar is setAdd OnCalendar= and reload
Failed to parse calendar specificationInvalid OnCalendar textTest it with systemd-analyze calendar "..."
Service fails with status=203/EXECExecStart path is wrong or not executableUse an absolute path, and chmod +x the script

Quick reference#

bash
crontab -e                          # edit your crontab
crontab -l                          # list it
# 30 3 * * * /path/job.sh >> /var/log/job.log 2>&1
systemd-analyze calendar "Mon..Fri 09:00"
sudo systemctl daemon-reload
sudo systemctl enable --now job.timer
systemctl list-timers --all
sudo systemctl start job.service    # run now
journalctl -u job.service -n 50

For a scheduled job that protects data, see backups and the 3-2-1 rule.

For a hands-on example of a scheduled container job, see rollback a failed Docker deploy.

Next#

Jobs often call out over the network. Learn the tools to debug that in Linux networking commands.

Check what you learned4 questions
1In a crontab, what does the schedule */15 * * * * mean?
2A cron job fails silently. What is the quickest way to see why?
3Which setting makes a timer run a missed job after the server was down?
4What must you do after creating or editing a .timer file?

Frequently asked questions

Should I use cron or a systemd timer?

Use cron for a simple recurring command on a machine you manage by hand. Use a systemd timer when you want journal logs, catch-up after downtime, resource limits or a dependency on another service.

What does Persistent=true do in a systemd timer?

If the machine was off or asleep at the scheduled time, the timer runs the job once when the system comes back. Cron skips missed runs.

Why does my cron job work in the terminal but not in cron?

Cron runs with a minimal environment, a short PATH and no login profile. Use absolute paths, set PATH in the crontab, and send output to a log file so you can see the error.

How do I list all systemd timers?

Run systemctl list-timers --all. It shows when each timer last ran, when it runs next and which service it triggers.

Sources

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios