Create systemd unit timers

· Alberto's Blog!

How to replace cron jobs with systemd timers.

Problem #

Run a script every day at midnight using systemd.

Solution #

1. Systemd service file #

 1# File: /etc/systemd/system/run-script.service
 2[Unit]
 3Description=Run a script every day at midnight
 4
 5[Service]
 6Type=simple
 7EnvironmentFile=/path/to/environment
 8ExecStart=/path/to/script.sh
 9
10[Install]
11WantedBy=multi-user.target

2. Systemd timer file #

 1# File: /etc/systemd/system/run-script.timer
 2[Unit]
 3Description=Run a script every day at midnight
 4
 5[Timer]
 6OnCalendar=*-*-* 00:00:00
 7Unit=run-script.service
 8
 9[Install]
10WantedBy=timers.target

3. Reload and start the timer #

1sudo systemctl daemon-reload
2sudo systemctl enable run-script.timer
3sudo systemctl enable run-script.service

Explanation #

The systemd unit timers are a powerful feature that allows you to schedule tasks to run at specific times or intervals. They are similar to cron jobs but offer more flexibility and control. You can take advantage of systemd's built-in capabilities like logging and monitoring, environment variables, and more.

last updated: