Timers provided by systemd can be used as cronjob replacements. More at man systemd.timer
.
Suppose we want to periodically trigger cleanup tasks for a baz
utility. We 'll create a baz-cleanup.service
which will
be triggered by a baz-cleanup.timer
.
Create a minimal service at /lib/systemd/system/baz-cleanup.service
:
[Unit]
Description=Baz Periodic Cleanup
[Service]
Type=simple
ExecStart=/usr/bin/python /opt/baz/cleanup.py
StandardError=journal
We dont provide an [Install] section, since this service is not meant to be enabled on its own (will be triggered by an enabled timer instead).
The actual task at /opt/baz/cleanup.py
could be something like:
#!/usr/bin/python
import logging
logging.basicConfig(level=logging.INFO)
logging.info("baz-cleanup: Running periodic cleanup for Baz ...")
Create the timer unit at /lib/systemd/system/baz-cleanup.timer
:
[Unit]
Description=Timer for Baz Cleanup
[Timer]
# Define target unit (in case the name part is the same, can be omitted)
Unit=baz-cleanup.service
## Activate target unit based on monotonic timers
# Time to wait after booting before we run first time
#OnBootSec=10min
# Time between running each consecutive time
#OnUnitActiveSec=30min
## or ..
## Activate target based on wallclock time (calendar event)
# Define a calendar event (see `man systemd.time`)
OnCalendar=*-*-* 12:13:00
[Install]
WantedBy=multi-user.target
Start the timer. Inspect the journal to verify that the perioric task is actually triggered.
systemctl daemon-reload && systemctl start baz-cleanup.timer