Systemd Timer Unit

Create a systemd timer as a modern replacement for cron jobs. Learn about OnCalendar syntax, persistent timers, and how timers pair with oneshot services.

Advanced Configurations

Detailed Explanation

Replacing Cron with systemd Timers

Systemd timers are a modern alternative to cron that provide better logging, dependency management, and reliability. A timer consists of two files: a .timer unit and a matching .service unit.

The Service Unit (runs the actual task)

[Unit]
Description=Daily Database Backup

[Service]
Type=oneshot
ExecStart=/opt/scripts/backup-database.sh
User=backup
Group=backup
StandardOutput=journal
StandardError=journal

The Timer Unit (schedules when to run)

[Unit]
Description=Run Database Backup Daily at 2 AM

[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
RandomizedDelaySec=300

[Install]
WantedBy=timers.target

OnCalendar Syntax

The OnCalendar= directive uses a flexible format:

Expression Meaning
*-*-* 02:00:00 Every day at 2:00 AM
Mon *-*-* 09:00:00 Every Monday at 9:00 AM
*-*-01 00:00:00 First day of every month
*-*-* *:00/15:00 Every 15 minutes
weekly Once a week (Monday 00:00)
daily Once a day (00:00)
hourly Once an hour (:00)

You can test expressions with systemd-analyze calendar "Mon *-*-* 09:00:00".

Persistent Timers

Persistent=true is crucial for reliability. If the system was powered off when the timer was supposed to fire, systemd will run the task immediately upon next boot. Without this, missed runs are simply skipped.

RandomizedDelaySec

RandomizedDelaySec=300 adds a random delay of up to 5 minutes. This prevents the "thundering herd" problem when multiple servers run the same timer — they won't all hit the database backup server simultaneously.

Advantages Over Cron

Feature Cron Systemd Timers
Logging Custom (redirect to file) Automatic (journal)
Missed runs Lost Persistent=true catches up
Dependencies None After=, Requires=
Resource limits None MemoryMax=, CPUQuota=
Calendar expressions 5-field Human-readable
Monitoring Check crontab systemctl list-timers
Email on failure MAILTO= OnFailure= integration

Enabling the Timer

sudo systemctl enable --now backup-database.timer
systemctl list-timers    # Verify it's scheduled

Use Case

Replacing cron jobs with systemd timers for scheduled database backups, log rotation, cache cleanup, or any recurring task that benefits from persistent execution, logging, and dependency management.

Try It — Systemd Unit File Generator

Open full tool