Run a timed service on Linux using Systemd
To run a timed service on Linux using systemd
, you can use the systemd-timer
unit, which is a built-in feature of systemd
that allows you to schedule tasks to run automatically at a specified time or interval.
To use systemd-timer
, you need to create a systemd
service that contains the command or script that you want to run. You can then create a systemd-timer
unit that specifies when and how often the service should be run.
Here’s an example of how to create a systemd-timer
unit that runs a service every hour:
First let’s make a service
You can checkout my indepth blog about creating a systemd service here: How to run anything as a service on Linux or view a summary below.
Create a systemd
service file for the service that you want to run. The service file should be named <name>.service
and should be placed in the /etc/systemd/system
directory. The file should contain the following sections:
[Unit] Description=<Description of the service> [Service] Type=simple ExecStart=<command or script to run> [Install] WantedBy=multi-user.target
For example, to create a service that runs a script named myscript.sh
, you can create a file named myscript.service
with the following content:
[Unit] Description=MyScript Service [Service] Type=simple ExecStart=/path/to/myscript.sh [Install] WantedBy=multi-user.target
Next lets make a timer for that service!
Create a systemd
timer file for the systemd-timer
unit. The timer file should be named <name>.timer
and should be placed in the /etc/systemd/system
directory. The file should contain the following sections:
[Unit] Description=<Description of the timer unit> [Timer] OnCalendar=<time or interval when the timer should run> [Install] WantedBy=timers.target
For example, to create a systemd-timer
unit that runs the myscript.service
service every hour, you can create a file named myscript.timer
with the following content:
[Unit] Description=MyScript Timer [Timer] OnCalendar=hourly [Install] WantedBy=timers.target
This timer file specifies that the myscript.service
service should be run every hour.
Enable and start the systemd-timer
unit. Once you have created the systemd
service and timer files, you can enable and start the systemd-timer
unit by running the following commands:
systemctl enable myscript.timer systemctl start myscript.timer
These commands will enable the myscript.timer
unit to start automatically when the system boots, and will start the unit immediately.
Check the status of the systemd-timer
unit. You can use the systemctl status myscript.timer
command to check the status of the myscript.timer
unit and see when it is scheduled to run next.
For more detailed instructions and examples, you can refer to the systemd
documentation for your Linux distribution. You can also search online for tutorials and guides that can help you use systemd-timer
to run timed services on Linux.
Written by Joel Gray
06/12/2022