Skip to content

Instantly share code, notes, and snippets.

@drmalex07
Last active May 11, 2023 19:17
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save drmalex07/350238961f451d6946dd to your computer and use it in GitHub Desktop.
Save drmalex07/350238961f451d6946dd to your computer and use it in GitHub Desktop.
An example systemd timer. #systemd #timer #systemd.timer #cron #cronjob

README

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.

Define the target service unit

Create a minimal service at /etc/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 ...")

Define the timer

Create the timer unit at /etc/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/Enable the timer

Start the timer. Inspect the journal to verify that the perioric task is actually triggered.

systemctl daemon-reload && systemctl start baz-cleanup.timer
@braindevices
Copy link

OnUnitActiveSec does not work with oneshot service, because oneshot service status is never active.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment