Systemd is a system and service manager for Linux operating systems. Systemctl is a command to introspect and control the state of the systemd system and service manager.
In order to run a service at specified time we need a timer to start service when needed.
Timers are systemd unit files whose name ends in .timer that control .service files or events. Timers can be used as an alternative to cron. Timers have built-in support for calendar time events, monotonic time events, and can be run asynchronously.
Let’s say we want to start openvpn service every week, Saturday at 12:30 then we want to stop it after running for 1 hour and 30 minutes. For this we will create a file in location /lib/systemd/system/openvpn.timer with the following content:
[Unit]
Description=Execute openvpn.service every week, Sat at 12:30
[Timer]
OnCalendar=Sat, 12:30
Unit=openvpn.service
[Install]
WantedBy=multi-user.target
With this done we need to apply a small change to our service in order to stop it after desired time. We will edit file /etc/systemd/system/openvpn.service adding the following line in the [Service] block:
RuntimeMaxSec=5400
With this change we will configures a maximum time for the service to run, time is in seconds.
With this changes done we will need to reload reload the systemd manager configuration. This will rerun all generators, reload all unit files, and recreate the entire dependency tree.
# systemctl daemon-reload
# systemctl start openvpn.timer
0 Comments