Systemd timers

Systemd Timers

Overview

  • activate a given systemd service on a predefined schedule
  • the choice between systemd timers and crontab entries: use whichever you prefer for any given task
  • you cant really choose system-wide one or the other, since software packages make their own choice, you a always have to check both when figuring out how a particular job gets run

Format

Systemd timers have 2 files:

  • the timer unit: schedule and the unit to activate
  • the service unit: what to run

selecting the service to run

  • by default, systemd looks for a service unit that has the same name as the timer.
  • You can specify a target unit explicitly with the Unit option.

timer options:

TypeTime basis
OnActiveSecRelative to the time at which the timer itself is activated
OnBootSecRelative to system boot time
OnStartupSecRelative to the time at which systemd was started
OnUnitActiveSecRelative to the time the specified unit was last active
OnUnitInactiveSecRelative to the time the specified unit was last inactive
OnCalendarA specific day and time

timing format examples:

Timer ExpressionMeaning
2017-07-04July 4th, 2017 at 00:00:00 (midnight)
Fri-Mon *-7-4July 4th each year, but only if it falls on Fri–Mon
Mon-Wed *-*-* 12:00:00Mondays, Tuesdays, and Wednesdays at noon
Mon 17:00:00Mondays at 5:00 p.m.
weeklyMondays at 00:00:00 (midnight)
monthlyThe 1st day of the month at 00:00:00 (midnight)
*:0/10Every 10 minutes, starting at the 0th minute
*-*-* 11/12:10:0At 11:10 and 23:10 every day

Commands

systemctl list-timers # list all timers
systemctl start systemd-tmpfiles-clean # run the target service directly (that is, independently of the timer, good for debugging)

# create a transient timer, this will be deleted on reboot
# get stored in /run/systemd/system
systemd-run --on-calendar '*:0/10' /bin/sh -c "cd /app && git pull"

To create your own timer:

  • drop .timer and .service files in /etc/systemd/system
  • if you want the timer to run at boot time add:
[Install]
WantedBy=multi-user.target