Cogs and Levers A blog full of technical stuff

Creating timer jobs with systemd

Creating and executing timer jobs has traditionally been a task for cron. With the arrival of systemd, this responsibility has been shifted onto services and timers. In today’s post, I’ll walk you through creating a service and timer schedule.

Setup

To accomplish this task, we need two files and a couple of shell commands. The basic method to do this is as follows:

  • Create a service definition
  • Create a timer definition
  • Start and enable the timer

In the example today, I’m going to schedule s3cmd each week to run over a mounted drive to sync with s3.

As we’re working with systemd, everything that we’ll do is a unit file.

Create a service definition

The service definition is a unit file which defines the actual work to be done. The following is placed at /etc/systemd/system/sync-to-s3.service.

[Unit]
Description=Runs the sync script for local file shares to s3

[Service]
Type=oneshot
ExecStart=/usr/bin/sh -c 's3cmd sync --check-md5 --follow-symlinks --verbose /mnt/share/ s3://my-s3-bucket/'

Full particulars on this file structure can be found in the documentation about service unit configuration.

Create a timer definition

The timer definition is also another unit file that defines a schedule. The following is named the same as the above, only it gets a .timer extension at /etc/systemd/system/sync-to-s3.timer.

[Unit]
Description=Schedules the sync of local file shares out to s3

[Timer]
OnCalendar=weekly
OnBootSec=10min

[Install]
WantedBy=multi-user.target

Again the documentation defines the full definition of the timer unit configuration.

The OnCalendar takes a value that needs to be understood by the time span parser, so make sure that it’s valid in accordance with the time span reference.

Start and enable the timer

Now that the service and schedule definitions have been created, we can start up the timer:

sudo systemctl start sync-to-s3.timer
sudo systemctl enable sync-to-s3.timer

Now that you’ve got your job up and running, you get the full feature set that systemd offers, including journald. You can use this to inspect the current or historical run logs from invocations:

sudo journalctl -u sync-to-s3