Skip to main content

Scheduling Tasks with Cron and Systemd Timers

Schedule reliable Linux tasks with cron and systemd timers, using proper logging, error handling and production-grade automation patterns.

30 Terms

Overview and What You Will Learn

Cron and systemd timers run commands at scheduled times, and a scheduled job is only reliable if it has absolute paths, logged output, protection against overlap and a way to notice when it stops running. Production servers always carry scheduled work such as nightly backups, certificate renewal, log cleanup and health checks. This lab assumes a Debian or Ubuntu server with PostgreSQL installed.

  • Reading and writing the five time fields of a crontab entry
  • Fixing the most common cron failure, a minimal PATH
  • Capturing job output so failures are never silent
  • Placing jobs system-wide with /etc/cron.d
  • Creating a systemd service and timer as the modern alternative
  • Building a backup job with locking, atomic writes and failure detection

Why This Matters in Production

A cron job that works by hand but fails under cron is one of the most frustrating bugs on Linux, and the cause is usually that cron runs with a minimal PATH and no profile. Imagine a team at a company like Stripe whose nightly database backup fails silently for months because of this. Nobody notices until the day they need a restore, and the backup is not there. Reliable scheduling means the job runs, logs its result, and raises an alarm when it does not.

Core Principles

A crontab line has five time fields followed by the command, and the job runs when all the fields match the current time.

Field Allowed values
Minute 0-59
Hour 0-23
Day of month 1-31
Month 1-12
Day of week 0-7 (0 and 7 are both Sunday)

Four symbols build the patterns: * means every value, , makes a list, - makes a range and / sets a step.

Entry Meaning
0 2 * * * Every day at 02:00
*/15 * * * * Every 15 minutes
0 9 * * 1-5 Weekdays at 09:00
0 0 1 * * First day of each month
30 23 * * 0 Sundays at 23:30
@reboot Once at boot
Security

A cron job runs with the permissions of the account that owns it. A root job that runs a world-writable script, or a script in a writable directory, lets any user become root. Keep scripts owned by root with mode 750 or stricter, in directories that other users cannot write.

Two traps affect the fields. If you restrict both day of month and day of week, cron runs the job when either one matches, not both. A literal % in a crontab command means newline, so it must be written as \%.

Systemd timers do the same job with a pair of units: a .timer that says when, and a .service that says what.

flowchart TD T[".timer unit
when to run"]:::tool --> S[".service unit
what to run"]:::tool S --> SC[Backup script]:::soft SC --> J[(journald logs)]:::ok classDef tool fill:#326CE5,color:#FFFFFF classDef soft fill:#DBEAFE,color:#1E293B classDef ok fill:#10B981,color:#FFFFFF
Feature cron systemd timer
Syntax Five compact fields OnCalendar expressions
Output Mailed to the user or lost Stored in journald
Missed runs Skipped unless anacron handles them Persistent=true catches up
Overlap Runs a second copy unless you lock A running service is not started again
Status No built-in command systemctl status and list-timers

Detailed Step-by-Step Practical Lab

Step 1 - Create and Manage Crontab Entries
Bash
crontab -e # edit your crontab
crontab -l # list it
sudo crontab -l # list root's crontab

Example entries. Lines starting with # are comments:

TEXT
MAILTO=""
# Database backup at 1 AM every night
0 1 * * * /opt/scripts/backup-postgres.sh >> /var/log/backup.log 2>&1
# Health check every 5 minutes
*/5 * * * * /opt/scripts/health-check.sh >> /var/log/health-check.log 2>&1
# Delete old logs every Sunday at 3 AM
0 3 * * 0 find /var/log/app -name "*.log" -mtime +30 -delete
# Warm the cache at 08:45 on weekdays
45 8 * * 1-5 /opt/scripts/warm-cache.sh >> /var/log/cache-warm.log 2>&1
Common Mistake

Typing crontab -r when you meant crontab -e. The -r flag deletes every entry with no confirmation and no undo. Keep a copy with crontab -l > ~/crontab.bak, and on Debian and Ubuntu use crontab -i -r or an alias that adds -i so it asks first.

Step 2 - Fix the Most Common Failure, PATH

Cron's default environment is minimal, typically PATH=/usr/bin:/bin and SHELL=/bin/sh. Find out what it really is:

Bash
# crontab entry: write cron's environment to a file, then remove the entry
# * * * * * env > /tmp/cron-env.txt 2>&1
diff <(env | sort) <(sort /tmp/cron-env.txt)
# Where your tools really live
command -v node python3 aws

There are three fixes, and the safest is the first: use absolute paths in the command, set PATH= at the top of the crontab, or set PATH inside the script:

Bash
# Bad: 0 1 * * * node /opt/app/report.js
# Good: 0 1 * * * /usr/local/bin/node /opt/app/report.js
Step 3 - Capture Output Reliably

By default cron tries to email output to the local user, and on a server with no mail setup it is lost:

Bash
# Append stdout and stderr to a log file
0 1 * * * /opt/scripts/backup.sh >> /var/log/backup.log 2>&1
# Send output to syslog and journald, tagged
0 1 * * * /opt/scripts/backup.sh 2>&1 | logger -t backup-cron
# Discard output, only for jobs you can afford to lose
*/5 * * * * /opt/scripts/metrics.sh > /dev/null 2>&1
Bash
journalctl -t backup-cron

Disable mail for the whole crontab with MAILTO="", or send it to a monitored address such as MAILTO=ops@devops.in. Log files grow without limit, so add a logrotate rule for anything you append to.

Step 4 - System-Wide Cron Locations

Cron also reads files that you drop into directories, without crontab -e:

Bash
ls /etc/cron.d/ /etc/cron.hourly/ /etc/cron.daily/ /etc/cron.weekly/ /etc/cron.monthly/
sudo tee /etc/cron.d/payment-health > /dev/null << 'EOF'
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
MAILTO=""
# Health check every 5 minutes, run as the payment-svc user
*/5 * * * * payment-svc /opt/payment/scripts/health-check.sh >> /var/log/payment-health.log 2>&1
EOF
systemctl status cron # Debian and Ubuntu
systemctl status crond # RHEL and Amazon Linux

Files in /etc/cron.d have a user field before the command, must be owned by root, and on Debian must use only letters, digits, underscores and hyphens in the filename, since a dot makes cron ignore the file. Scripts in /etc/cron.daily and the other directories must be executable and follow the same naming rule. Their exact run time is decided by the system, so use /etc/cron.d when the time matters.

Step 5 - Build a Production Backup Script

This script uses an explicit PATH, strict mode, an atomic write so a failed run never leaves a half-written file, a gzip integrity check, retention cleanup, and a success marker for monitoring:

Bash
sudo mkdir -p /opt/scripts /opt/backups/postgres /var/lib/backup
sudo tee /opt/scripts/backup-postgres.sh > /dev/null << 'SCRIPT'
#!/usr/bin/env bash
set -euo pipefail
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
BACKUP_DIR=/opt/backups/postgres
RETENTION_DAYS=7
DATE=$(date +%Y%m%d-%H%M%S)
FINAL="$BACKUP_DIR/mydb-$DATE.sql.gz"
TMP="$FINAL.partial"
echo "Starting backup at $(date)"
trap 'rm -f "$TMP"' EXIT
/usr/bin/pg_dump mydb | gzip > "$TMP"
gzip -t "$TMP"
mv "$TMP" "$FINAL"
echo "Backup created: $FINAL ($(du -sh "$FINAL" | cut -f1))"
find "$BACKUP_DIR" -name "*.sql.gz" -mtime +"$RETENTION_DAYS" -delete
touch /var/lib/backup/postgres-last-success
echo "Backup completed at $(date)"
SCRIPT
sudo chown root:postgres /opt/scripts/backup-postgres.sh
sudo chmod 750 /opt/scripts/backup-postgres.sh
sudo chown postgres: /opt/backups/postgres /var/lib/backup

Run it as the postgres user so pg_dump can authenticate without a password prompt, and wrap it in flock so a slow run cannot overlap the next one. Add this to the postgres user's crontab:

Bash
sudo crontab -u postgres -e
TEXT
0 1 * * * /usr/bin/flock -n /var/lock/backup-postgres.lock /opt/scripts/backup-postgres.sh >> /var/log/backup.log 2>&1

Detect a job that stopped running, not just one that failed. Alert if the success marker is older than 26 hours:

Bash
find /var/lib/backup/postgres-last-success -mmin -1560 | grep -q . \
|| echo "ALERT: PostgreSQL backup has not succeeded in 26 hours"
Step 6 - Create a systemd Timer

The service unit says what runs:

Bash
sudo tee /etc/systemd/system/db-backup.service > /dev/null << 'EOF'
[Unit]
Description=PostgreSQL Database Backup
After=postgresql.service
[Service]
Type=oneshot
User=postgres
ExecStart=/opt/scripts/backup-postgres.sh
EOF

The timer unit says when. Its name must match the service, and Persistent=true runs a missed job at the next boot:

Bash
sudo tee /etc/systemd/system/db-backup.timer > /dev/null << 'EOF'
[Unit]
Description=Daily PostgreSQL backup timer
[Timer]
OnCalendar=*-*-* 01:00:00
Persistent=true
RandomizedDelaySec=300
[Install]
WantedBy=timers.target
EOF

Check the schedule before you enable it, then enable the timer and run the service once to test it:

Bash
systemd-analyze calendar "*-*-* 01:00:00"
sudo systemctl daemon-reload
sudo systemctl enable --now db-backup.timer
systemctl list-timers db-backup.timer
# NEXT LEFT UNIT ACTIVATES
# Thu 2026-10-15 01:00:00 IST hours db-backup.timer db-backup.service
sudo systemctl start db-backup.service
journalctl -u db-backup.service -n 20

Production Best Practices & Common Pitfalls

Tip

Add OnFailure= to a service so systemd starts an alerting unit whenever the job fails. With cron you only learn about a failure if you read the log or built a separate check.

Remember

Cron uses the server's time zone, and daylight saving shifts can skip or repeat a run. Keep servers on UTC, or in a zone without daylight saving such as Asia/Kolkata, and check that your jobs agree.

Mistake Problem Fix
Relative commands in the job Works by hand, fails in cron Absolute paths, or PATH= set explicitly
No output redirection Silent failures and no debugging trail >> logfile 2>&1 or logger
Script not executable Cron fails with only a log line chmod +x and check the owner
Job overlaps itself Two copies fight over the same files flock -n, or a systemd service
Unescaped % in a crontab line The command is cut at the % Write \% or move the logic into a script
Only checking for failures A job that never runs looks healthy A success marker with a freshness alert
  • Test a restore, not just a backup. Restore the latest dump into a scratch database on a schedule, because a dump that cannot be restored is not a backup.
  • Keep secrets out of crontabs. Crontab files are readable by root and visible in process listings, so use ~/.pgpass, peer authentication or a secrets manager.
  • Prefer timers for jobs with dependencies. After=, resource limits and journald logging are simpler in a unit than in a crontab line.

Quick Reference & Troubleshooting Commands

Task Command
Edit your crontab crontab -e
List your crontab crontab -l
Edit another user's crontab sudo crontab -u USER -e
List timers systemctl list-timers
Run a timed job now sudo systemctl start NAME.service
Read a job's logs journalctl -u NAME.service
Read cron-tagged logs journalctl -t TAG
Validate a timer schedule systemd-analyze calendar "EXPRESSION"
Check the cron daemon systemctl status cron
Prevent overlapping runs flock -n /var/lock/NAME.lock COMMAND

Resources

Explore More in Linux Process and System Management

All 6 Topics

Frequently Asked Questions

Is Scheduling Tasks with Cron and Systemd Timers free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Scheduling Tasks with Cron and Systemd Timers topic cover?

Schedule reliable Linux tasks with cron and systemd timers, using proper logging, error handling and production-grade automation patterns.

Found a mistake, an outdated step or a broken link?