Systemd timers

Systemd timers are a nice way to run scheduled jobs on your server, some of their advantages:

  • Can schedule jobs with sub-second frequency (though in case of high frequency jobs this might not be an optimal solution!)
  • You can easily start the job manually, in exactly the same enviornment that it will be run by trigger;
  • Built-in on many systems;
  • You already know how to create service files ;);

So here is how they work:

  • You create a service that runs your job, and then exits;
  • Then you create a systemd timer that launches beforementioned timer;

Simplest example

Create file named backups.service and put it into /etc/systemd/system.

[Unit]
Description=Backups command
After=syslog.target

[Install]
WantedBy=

[Service]
Restart=on-failure
Type=simple
ExecStart=/usr/local/bin/backup-script.sh
WorkingDirectory=/backups
StandardError=syslog
NotifyAccess=all

Create file named backups.timer and put it into /etc/systemd/system:

[Unit]
Description=Backups Timer

[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true

[Install]
WantedBy=timers.target

Some important points:

  • Timer file should have the same name as service file, that is: backups.timer will launch service named backups.service (you can costumize this)
  • Service type should be simple;
  • Setting WantedBy= ensures that this service is not launched during boot-up procedure;
  • This calendar means Daily at 2AM, you can use e.g. weekly or daily, full description is here.

Then install both service files, and you are good to go.

To start one-off job just manually start backups service.