Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Prototype-X/2a96eb665c50fd6696ecaa389abafc48 to your computer and use it in GitHub Desktop.
Save Prototype-X/2a96eb665c50fd6696ecaa389abafc48 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 /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 ...")

Define the timer

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/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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment