Saturday, January 21, 2023

Scheduling Tasks With systemd.timer

Systemd.timer is a way to scheduling jobs and tasks in systemd based linux system. The systemd timer units are identified by ".timer" (dot timer) file name extension, compared to ".service" for service units. 

Each timer file requires a service file for it to work. In other word, systemd timers only can schedule systemd services.  

Some of systemd.timer features:
  1. timer is managed by systemd similar to other units, using systemctl command
  2. timers can be triggered by calendar event, or triggered by specific time elapsed from a certain starting point
  3. time units are logged to journal, for easier troubleshooting and monitoring
  4. if the system is off during the expected execution time, the timer will be executed when the system is running again
The usage of timer is best explained using an example. Let's say we want to create a timer to run a script called hello.sh.

First, we need to create the script, and get the location of the script. Let's say we created the script inside /usr/local/bin/hello.sh

Next, we need to create a systemd service unit for the above script. Just insert below settings into /etc/systemd/system/hello.service
[Unit]
Description="Hello app"

[Service]
ExecStart=/usr/local/bin/hello.sh

Then, create a systemd timer unit for hello.service. Just add below setting into /etc/systemd/system/hello.timer
[Unit]
Description="Run hello.service 5min after boot, every 24 hours relative to activation time, and everyday at 10:00 am"

[Timer]
OnBootSec=5min
OnUnitActiveSec=24h
OnCalendar=Mon..Fri *-*-* 10:00:*
Unit=helloworld.service

[Install]
WantedBy=multi-user.target

The above example will run the script after 5 minutes of system boot, 24 hours after the timer activation time, and everyday at 10:00am. The format for OnCalendar is as below
Day of Week = Sun to Sat
Date = in yyyy-mm-dd format
Time = in hour:minute:seconds format

For example, if we want to execute the script at 3:00 pm every Monday and Friday
OnCalendar=Mon,Fri *-*-* 15:00:00
Or execute the script at 4:00 pm 20 February 2023
OnCalendar=2023-02-20 16:00:00

For more example on setting the timer, we can type this command to see the manual page of systemd.time
# man 7 systemd.time

Before we use the new systemd unit files for hello.sh, we can verify that they are error free
# systemd-analyze verify /etc/systemd/system/hello.*

If no error detected, then we can start the timer
# systemctl start hello.timer

We can also enable the timer on boot
# systemctl enable hello.timer

To check the status of timer
# systemctl status hello.timer

To list all active timers
# systemctl list-timers 

To list all timers, regardless whether they are active or note
# systemctl list-timers --all

To stop the timer
# systemctl stop hello.timer

No comments:

Post a Comment