Instead of using a cronjob placed in our crontab, we can make use of a systemd timer on a modern linux system which is running systemd.
For a systemd timer to work, it needs two parts.
One part consists of a
.timer file, and a
.timer file specifies when our service should be started. Just like a cronjob we can specify here on which days, in which week or at which time our service should be started.
.service file contains all the details about the script or command we want to run.
Example systemd timer file
Description=restic backup timer
The syntax of systemd timers is a little bit different from a cronjob. In this example we start our service with
OnCalendar every 12h.
There are many different timer settings that execute the service at different times.
OnBootSec=1h 30m would start our service 1h 30m after the last boot of the system. One time only. So rather not suitable for a cronjob.
Example systemd service file
Description=restic backup cron
ExecStart=/usr/bin/python3 /opt/restic/resticBackup.py backup
ExecStart can be used to run a command or a script.
In this example this systemd service would run a python script to create a restic backup of our system.
It is important in this example that the timer and the service both have the same name, in this case:
Enable systemd timer
As soon as you have created your
.service file you need to enable them once.
systemctl enable --now example.timer
--now starts the timer immediately after entering the command.
Otherwise we would have to wait for the next reboot before the timer is started.
For testing, it is also possible to restart the timer with
systemctl restart example.timer. The service is then executed immediately and then repeated after n time as specified in the timer.
With the following command you can see when your service will be executed next time and when the service was started last time.