Systemd - Periodically run a command, script, process, or service

To set up a periodic script, follow these steps. Note vim is used as the example text editor, and a $ denotes a command for the terminal as opposed to text in a file. In this example the path to the script is /path/to/script_name.sh; replace this with the path of your script.

  1. Make executable the script which you want to periodically ran.
$ chmod +x /path/to/script_name.sh
  1. Create a .service file which executes the script:
$ vim ~/.config/systemd/user/script_name.service

and enter the following in the file:

[Unit]
Description=periodic execution of script_name.sh
[Service]
ExecStart=/path/to/script_name.sh
  1. Create a .timer which activates the .service file periodically:
$ vim ~/.config/systemd/user/script_name.timer

and enter the following in the file:

[Unit]
Description=Timer to periodically trigger script_name.service

[Timer]
OnCalendar=weekly # defines the periodicity of the script
Persistent=true # decides whether the counting of time persists after the computer is switched off, or not (false = only count time when switched on)

[Install]
WantedBy=timers.target
  1. Enable the executing service to function dependant on the timer:
$ systemctl --user enable script_name.service script_name.timer

Then start the service:

$ systemctl --user start script_name.service script_name.timer
  1. Check the timer is running by:
$ systemctl --user list-timers

If all is correct, the output should show the service having just PASSED, and the LEFT amount should roughly be the period initially set. If incorrectly set, you may see your timer as inactive in the output of $ systemctl --user list-timers -all. Consult any error messages or search online for help if this occurs.

Have fun :)

PKGBUILD, AUR - Making a PKGBUILD (for the AUR)