Cron & Systemd Timers – Master Modern Scheduling with Ease

Cron & Systemd Timers

Photo by Djim Loic on Unsplash

When you’re running a server or even a home‑lab machine, “automation” is the word that keeps everything humming. From nightly backups to daily health checks, you need a reliable way to fire commands on a schedule. For decades cron has been the go‑to daemon in Unix‑like systems, but the newer systemd timers are gaining traction for their richer feature set and tighter integration with service units.

This article dives into both worlds, shows when each shines, and walks you through concrete examples – including how to monitor your jobs so that a missed run doesn’t go unnoticed.


Why Scheduling Still Matters

  • Consistency: Regularly running cleanup scripts keeps disk space in check.
  • Reliability: Automated backups protect against accidental data loss.
  • Observability: Knowing whether a job ran helps spot underlying system issues (e.g., a stuck process, low memory).

If you’re setting up a new server or tightening your CI/CD pipeline, picking the right scheduler is one of the first decisions that will shape maintenance overhead for years.


1. Cron – The Classic Scheduler

1.1 What Is It?

Cron is a background service (crond) that reads /etc/crontab and per‑user crontabs (usually ~/crontab). Each line contains a time specification followed by the command to run.

# ┌───────────── minute (0-59)
# │ ┌───────────── hour   (0-23)
# │ │ ┌───────────── day of month (1-31)
# │ │ │ ┌───────────── month (1-12)
# │ │ │ │ ┌───────────── day of week (0-6) (Sunday=0)
# │ │ │ │ │
# * * * * * command to execute

1.2 Strengths

Feature Cron
Simplicity A single file, plain text.
Wide adoption Almost every Unix system ships with it.
User‑level crontabs No root required for personal jobs.

1.3 Gotchas

  • Environment – Cron runs with a minimal environment (PATH=/usr/bin:/bin). Scripts that rely on user profiles or custom env vars need explicit export statements.
  • Logging – By default, output goes to the user’s mailbox unless redirected. For robust logs you must redirect stdout/stderr manually.
  • Granularity – The smallest unit is one minute; no native support for seconds.

2. Systemd Timers – The Next‑Gen Scheduler

2.1 What Is It?

Systemd timers are a pair of unit files: a service (*.service) that defines the task, and a timer (*.timer) that schedules it. They live under /etc/systemd/system/ or ~/.config/systemd/user/.

# backup.service
[Unit]
Description=Daily backup

[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh
# backup.timer
[Unit]
Description=Run daily backup at 02:00

[Timer]
OnCalendar=daily
Persistent=true

[Install]
WantedBy=timers.target

2.2 Strengths

Feature Systemd Timer
Fine‑grained scheduling – Seconds, cron‑style expressions (OnCalendar=* *:30:00), or relative delays (OnActiveSec=).
Integrated logging – Uses journalctl, no need to redirect output.
Dependency management – Timers can depend on other units; start only after network is up, etc.
Per‑user timers – No root needed for user jobs (via systemctl --user).
Automatic restart – If a service fails, systemd can retry automatically.

2.3 When to Prefer Timers

  • You need exact start times or complex recurrence patterns.
  • Your job must run only after another service is active.
  • You want centralized logs and easy enable/disable via systemctl.

3. Practical Example – Daily Backup with Monitoring

Let’s build a complete workflow:

  1. Script: /usr/local/bin/backup.sh
  2. Timer: daily-backup.timer
  3. Monitoring: Healthchecks.io ping on success.

3.1 The Backup Script

#!/usr/bin/env bash
set -euo pipefail

BACKUP_DIR="/var/backups"
TIMESTAMP=$(date +%Y%m%d-%H%M)
DEST="$BACKUP_DIR/backup-$TIMESTAMP.tar.gz"

# Example: tar the home directory (adjust as needed)
tar czf "$DEST" /home/user

# Ping Healthchecks.io to signal success
curl -s https://hc-ping.com/YOUR-UNIQUE-PING-URL > /dev/null

Why set -euo pipefail? It makes the script exit on any error, preventing a silent failure that wouldn’t ping Healthchecks.

3.2 Systemd Service

Create /etc/systemd/system/daily-backup.service:

[Unit]
Description=Daily backup job
After=network-online.target

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

3.3 Systemd Timer

Create /etc/systemd/system/daily-backup.timer:

[Unit]
Description=Run daily backup at 02:00 local time

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

[Install]
WantedBy=timers.target
  • Persistent=true ensures that if the machine was off at 2 AM, the job runs immediately on boot.
  • AccuracySec=1min keeps it close to the exact minute without waking the CPU too often.

3.4 Enable and Start

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

Check status:

systemctl list-timers | grep daily-backup
journalctl -u daily-backup.service --since "1 day ago"

3.5 Healthchecks.io Integration

  • Create a new check in your Healthchecks account.
  • Copy the ping URL into backup.sh (replace YOUR-UNIQUE-PING-URL).
  • Configure Period to match the timer’s frequency (daily → 24 h) and Grace Time to allow for any expected lag (e.g., 30 min).

Healthchecks will now alert you if a backup fails or doesn’t run on time.


4. One‑Time vs Recurring Jobs

Requirement Cron Systemd Timer
One‑time Use at command or add a line to /etc/crontab with @reboot and remove it after execution. Use OnActiveSec= or OnCalendar= with Persistent=false; systemd will automatically stop the timer after first run.
Recurring Classic * * * * * command. OnCalendar=hourly, daily, cron‑style (OnCalendar=* *:30) or relative delays.

Systemd timers make one‑time jobs trivial with a single unit file, whereas cron requires manual cleanup.


5. Troubleshooting Common Issues

Symptom Likely Cause Fix
Job never runs Timer not enabled (systemctl status my.timer shows inactive) sudo systemctl enable --now my.timer
No output in logs Service not writing to stdout/stderr Check StandardOutput=journal (default). Use journalctl -u my.service.
Environment variables missing Cron’s minimal env In a cron job, source /etc/profile or export needed vars. With systemd, add them under [Service] (Environment=).
Time drift on backup times NTP not synchronized Ensure timedatectl set-ntp true.

6. Choosing the Right Tool

Scenario Recommended Scheduler
Legacy scripts that already run via cron and you’re comfortable editing crontabs Keep using cron; it’s lightweight.
Complex dependencies (e.g., “run after database is ready”) Use systemd timers with After= directives.
Per‑user automation on a desktop without root access Systemd user timers (systemctl --user).
Need centralized logs and easy enable/disable Systemd timers.
Quick one‑time tasks at or cron + manual removal.

7. Takeaway Checklist

  • [ ] Decide whether you need the granularity of systemd timers.
  • [ ] Write your script with robust error handling (set -euo pipefail).
  • [ ] Create a systemd service and timer (or cron line) that matches your schedule.
  • [ ] Enable the timer and verify it runs (systemctl status, journalctl).
  • [ ] Add monitoring – Healthchecks.io or similar – to get alerts on failures.
  • [ ] Document the job in a README or internal wiki so future maintainers know what’s scheduled.

By pairing systemd timers with an external health‑check service, you not only automate tasks but also gain visibility into their execution. That small extra layer of observability turns a silent failure into a prompt alert, saving you from days of troubleshooting later.

Happy scheduling!

Frequently Asked Questions (FAQ)

What are the main differences between cron and systemd timers?

Cron is a simple, widely‑used daemon that schedules jobs with minute‑level granularity and minimal environment support. Systemd timers offer finer control (seconds, relative delays), integrated logging via journalctl, dependency handling, and per‑user units without root.

How do I enable or disable a systemd timer?

Use the standard systemctl commands:

sudo systemctl enable --now mytimer.timer   # Enable and start immediately
sudo systemctl disable mytimer.timer         # Stop and prevent future starts

For user timers, replace systemctl with systemctl --user.

Can I redirect output from a cron job to a file?

Yes. Append redirection in the crontab entry:

* * * * * /path/to/script.sh >> /var/log/myscript.log 2>&1

This captures both stdout and stderr into myscript.log.

How can I make a systemd timer run only after the network is up?

Add a dependency in the service unit:

[Unit]
After=network-online.target
Wants=network-online.target

Then the associated timer will start the service only once the network is available.

Related Articles

0 0 votes
Article Rating
guest
0 Comments
Oldest
Newest Most Voted
Scroll to Top