31. Systemd Timers
31.1 What is a systemd Timer?
Section titled “31.1 What is a systemd Timer?”A systemd Timer is a specialized systemd unit file ending in .timer that acts as an alarm clock. Its sole responsibility is to trigger a matching .service unit when a specific calendar time or elapsed duration is reached.
Architecture: The 2-Unit Decoupled Model
Section titled “Architecture: The 2-Unit Decoupled Model”Unlike Cron—where timing and the command to execute are bundled in a single line—systemd timers decouple the Schedule from the Action:
mybackup.timer (Defines WHEN to run: e.g., OnCalendar=*-*-* 02:00:00) │ │ triggers ▼ mybackup.service (Defines HOW to run: User, Environment, Resource limits) │ ▼ /opt/scripts/backup.sh (The actual shell script or application binary)- The Timer Unit (
mybackup.timer): Specifies the time intervals or events that trigger execution. - The Service Unit (
mybackup.service): A standardoneshotservice defining the executable command, environment variables, working directory, and user privileges.
[!NOTE] By convention, if
mybackup.timerhas the exact same name asmybackup.service(except for the file extension), the timer will automatically trigger that service without requiring an explicitUnit=declaration.
31.2 Types of Timers: Monotonic vs Realtime (Calendar)
Section titled “31.2 Types of Timers: Monotonic vs Realtime (Calendar)”Systemd timers fall into two categories:
1. Realtime / Calendar Timers (OnCalendar=)
Section titled “1. Realtime / Calendar Timers (OnCalendar=)”Triggers at an absolute calendar date and time (equivalent to traditional Cron).
[Timer]# Run every day at 02:00 AM UTCOnCalendar=*-*-* 02:00:00# Run every Monday at 04:30 AMOnCalendar=Mon *-*-* 04:30:00# Run every 15 minutesOnCalendar=*:0/152. Monotonic Timers (Relative to an Event)
Section titled “2. Monotonic Timers (Relative to an Event)”Triggers relative to a changing timer or system event:
OnBootSec=: Triggers a specific duration after the system boots up.OnBootSec=15minOnUnitActiveSec=: Triggers a specific duration after the service was last activated. Ideal for repeating tasks where you want a delay between consecutive runs regardless of how long the previous run took!OnUnitActiveSec=1hOnStartupSec=: Triggers relative to when the systemd manager itself was started.
31.3 Persistent Timers (Persistent=true)
Section titled “31.3 Persistent Timers (Persistent=true)”One of Cron’s biggest flaws is that if a server is powered off or suspended when a scheduled job was supposed to fire (e.g., at 02:00 AM), Cron simply skips the job entirely.
Systemd solves this with the Persistent=true directive:
[Timer]OnCalendar=*-*-* 02:00:00Persistent=true- When
Persistent=trueis enabled, systemd stores a timestamp on disk (/var/lib/systemd/timers/) each time the timer triggers. - If the machine was powered off during the scheduled time, systemd detects the missed execution upon boot and triggers the service immediately!
31.4 Step-by-Step Implementation: Building a Production Timer
Section titled “31.4 Step-by-Step Implementation: Building a Production Timer”Let’s build a production-grade automated database backup timer that runs daily at 02:30 AM.
Step 1: Create the Service Unit (/etc/systemd/system/db-backup.service)
Section titled “Step 1: Create the Service Unit (/etc/systemd/system/db-backup.service)”[Unit]Description=Database Backup ServiceAfter=network.target
[Service]Type=oneshotUser=postgresGroup=postgresWorkingDirectory=/var/backupsExecStart=/usr/local/bin/backup_database.sh
# Resource limits (cgroups)MemoryMax=2GCPUQuota=50%
# Security hardeningProtectSystem=strictReadWritePaths=/var/backupsPrivateTmp=true[!TIP] Notice that
db-backup.servicedoes not have an[Install]section because it is not meant to be enabled directly; it will be triggered by its timer!
Step 2: Create the Timer Unit (/etc/systemd/system/db-backup.timer)
Section titled “Step 2: Create the Timer Unit (/etc/systemd/system/db-backup.timer)”[Unit]Description=Daily Database Backup Timer
[Timer]# Run every morning at 02:30:00OnCalendar=*-*-* 02:30:00
# Catch up if machine was off during scheduled timePersistent=true
# Add randomized jitter (up to 5 minutes) to prevent cluster resource spikesRandomizedDelaySec=300
[Install]WantedBy=timers.targetStep 3: Enable and Start the Timer
Section titled “Step 3: Enable and Start the Timer”# 1. Reload systemd daemon to recognize new filessudo systemctl daemon-reload
# 2. Enable the timer to start on bootsudo systemctl enable db-backup.timer
# 3. Start the timer immediatelysudo systemctl start db-backup.timer
# 4. Check timer statussystemctl status db-backup.timer31.5 Inspecting & Managing Timers
Section titled “31.5 Inspecting & Managing Timers”List All Active Timers (systemctl list-timers)
Section titled “List All Active Timers (systemctl list-timers)”Displays a comprehensive, sorted view of all scheduled timers across the entire system:
systemctl list-timersExample output:
NEXT LEFT LAST PASSED UNIT ACTIVATESSat 2026-10-03 17:00:00 UTC 44min left Sat 2026-10-03 16:00:02 UTC 15min ago logrotate.timer logrotate.serviceSun 2026-10-04 02:30:00 UTC 10h left Sat 2026-10-03 02:30:01 UTC 13h ago db-backup.timer db-backup.serviceSun 2026-10-04 03:10:00 UTC 11h left n/a n/a fstrim.timer fstrim.serviceManual Triggering (Testing the Service)
Section titled “Manual Triggering (Testing the Service)”You do not need to wait until 02:30 AM to test your script. You can trigger the underlying .service manually at any time:
# Manually run the service immediatelysudo systemctl start db-backup.service
# Inspect the execution logs in journalctlsudo journalctl -u db-backup.service --no-pagerValidating OnCalendar Expressions with systemd-analyze
Section titled “Validating OnCalendar Expressions with systemd-analyze”Before committing a complex schedule, test and verify how systemd interprets your timing syntax:
systemd-analyze calendar "Mon,Wed,Fri *-*-* 03:00:00"Output confirms the normalized form and exact timestamp of the next execution.
31.6 Cron vs systemd Timers: Comprehensive Comparison
Section titled “31.6 Cron vs systemd Timers: Comprehensive Comparison”| Feature | Traditional Cron | Modern systemd Timer |
||||
| Architecture | Single daemon (cron/crond) | Core init system component (systemd) |
| Configuration | Single-line crontab format (* * * * * cmd) | Declarative dual-unit architecture (.timer + .service) |
| Logging | Basic syslog / silent / requires >> file.log 2>&1 | Full native journalctl integration with stdout/stderr capture |
| Missed Jobs (Power Off) | Skipped completely | Automatically caught up with Persistent=true |
| Dependencies | None (blindly fires commands) | Full After=, Requires=, Wants= dependency support |
| Resource Control | None (runaway script can crash server) | Native cgroups integration (MemoryMax=, CPUQuota=) |
| Security Hardening | Limited to user permissions | Sandboxing (ProtectSystem=, PrivateTmp=, NoNewPrivileges=) |
| Timing Flexibility | Calendar only (min resolution: 1 minute) | Monotonic (relative to boot/last run) + Calendar (millisecond resolution) |
| Cluster Jitter | None | RandomizedDelaySec= avoids “thundering herd” spikes |
| Status Inspection | Difficult (crontab -l + manual log grep) | systemctl list-timers gives clean overview with countdown timers |
31.7 When Should You Use Which?
Section titled “31.7 When Should You Use Which?”- Use Cron when: You are writing quick, simple, user-level recurring scripts, operating on legacy Unix/Linux systems (FreeBSD, Alpine with OpenRC), or when a 1-line crontab is all that is required.
- Use systemd Timers when: You are running enterprise production services on modern Linux (Ubuntu, Debian, RHEL, Fedora), when tasks require strict logging via
journalctl, when jobs must survive reboots (Persistent=true), or when scripts need memory and CPU resource throttling.