💾 Archived View for sylvaindurand.org › from-cron-tasks-to-systemd-timers › index.gmi captured on 2022-04-28 at 17:50:55. Gemini links have been rewritten to link to archived content
-=-=-=-=-=-=-
Like the vast majority of users of Linux systems, I have long used cron tasks when it came to running tasks at regular intervals.
The tasks to be performed are to be entered in a text file, accessible from `crontab -e`:
# m h dom mon dow command
The disadvantages are multiple. The smallest unit of time is the minute. It is not possible to easily activate, deactivate, start or stop a command. Finally, it is very hard to see or simulate what is really happening.
Nowadays, many Linux distributions embed `systemd`, which makes it easy to perform this kind of operations.
With `systemd`, it's all about services. Here is an example to create a very simple service:
# /etc/systemd/system/myservice.service [Service] Type=oneshot ExecStart=path/to/script.sh # WorkingDirectory=/home/user/path/ # User=user
It indicates that the script must be started only once, and its address. But it is also possible to indicate the working directory, the user who launches it... And even more if other services are needed, when to launch it, etc.
You can check that everything works fine with `systemctl start myservice`.
The timer will have the same name, but will end with `.timer`:
# /etc/systemd/system/myservice.timer [Timer] OnCalendar=*:*:0/10 [Install] WantedBy=timers.target
The `OnCalendar` line allows you to specify the frequency, or the activation date. The most frequent synthesis is `*-*-* *:*:*`, with the date and time. In the example above, the script is launched every 10 seconds.
In order for our changes to be taken into account, we need to run the following command, the files being cached:
systemctl daemon-reload
Finally, the timer is launched, making sure that it restarts at startup:
systemctl enable --now myservice.timer