Creating Systemd Timer Jobs
Systemd Timer Jobs
In the past, it would be fairly typical to use cron to schedule jobs on Linux or BSD. Cron is an excellent tool for scheduling simple jobs, but weaknesses will begin to appear when complexity is required.
Some of the benefits of systemd include:
- Automatic rotaion of logs.
- Memory/CPU scheduling.
- Random start/job delays.
We’ll cover services and timers today.
Timers
The first step to creating a recurring job using systemd is to create the timer unit itself. This file controls the schedule of the job.
In this example, let’s create a timer that runs every 15 minutes, and up to 30 minutes determined by a delay.
/etc/systemd/system/run-job.timer
[Unit]
Description=Run service every 15-30 minutes
Requires=run-job.service
[Timer]
Unit=run-job.service
OnUnitInactiveSec=15m
RandomizedDelaySec=15m
# Nanosecond accuracy is possible, but it's not required here.
AccuracySec=1s
[Install]
WantedBy=timers.target
Note that, the service and timer must share the same name, and that the extension must be ‘.timer’ for the timer and ‘.service’ for the service.
Services
In this example service, we are running a simple python script (or any other application that you want). Make sure that you are using the full path to the application
/etc/systemd/system/run-job.service
[Unit]
Description=Repeatedly runs a python script.
Type=oneshot # our script does a single thing and then exits.
Wants=run-job.timer
[Service]
ExecStart=/usr/bin/python3 /home/username/pythonscript.py --options yes
User=username
Group=username
[Install]
WantedBy=multi-user.target
Running the Job
From here on out, running the job is as simple as enabling it, just like any other systemd service. Simply call the command
systemctl enable run-job
This will kick of the job running the python script specified in the unit file. To stop the service from running simply issue the opposite command:
systemctl disable run-job