Linux / Bash
Beginner
1 min read
Systemd Timers as a Modern Cron Alternative
Example
# ---- List active timers ----
systemctl list-timers
systemctl list-timers --all # Include inactive timers
# ---- Create a systemd timer ----
# Step 1: Create the service unit
# sudo nano /etc/systemd/system/mybackup.service
# Contents of mybackup.service:
# [Unit]
# Description=Daily database backup
# After=network.target
#
# [Service]
# Type=oneshot
# User=backup
# ExecStart=/usr/local/bin/backup_db.sh
# StandardOutput=journal
# StandardError=journal
# Step 2: Create the timer unit
# sudo nano /etc/systemd/system/mybackup.timer
# Contents of mybackup.timer:
# [Unit]
# Description=Run daily database backup at 2 AM
# Requires=mybackup.service
#
# [Timer]
# OnCalendar=*-*-* 02:00:00
# Persistent=true
# RandomizedDelaySec=300
#
# [Install]
# WantedBy=timers.target
# Step 3: Enable and start the timer
sudo systemctl daemon-reload
sudo systemctl enable --now mybackup.timer
sudo systemctl status mybackup.timer
# ---- OnCalendar examples ----
# Daily at 2:00 AM: *-*-* 02:00:00
# Every Monday at 6 AM: Mon *-*-* 06:00:00
# Every 15 minutes: *:0/15
# Hourly: hourly (shorthand)
# Daily: daily
# Weekly: weekly
# Monthly: monthly
# ---- Timer management ----
sudo systemctl start mybackup.timer # Start now
sudo systemctl stop mybackup.timer # Stop timer
sudo systemctl disable mybackup.timer # Disable on boot
# Run the associated service immediately (test)
sudo systemctl start mybackup.service
# View logs for the service
journalctl -u mybackup.service
journalctl -u mybackup.service --since "1 hour ago"
Related Resources
Linux / Bash Reference
Complete tag & property list
Linux / Bash How-To Guides
Step-by-step practical guides
Linux / Bash Exercises
Practice what you've learned
More in Linux / Bash
This is the last lesson in this section.
Create a free account to earn a certificate