knowledge/technology/linux/systemd/Systemd-Timers.md

2.4 KiB

obj arch-wiki
concept https://wiki.archlinux.org/title/Systemd/Timers

Systemd Timers

Timers are systemd unit files with a suffix of .timer. Timers are like other unit configuration files and are loaded from the same paths but include a [Timer] section which defines when and how the timer activates. Timers are defined as one of two types:

  • Realtime timers (a.k.a. wallclock timers) activate on a calendar event, the same way that cronjobs do. The option OnCalendar= is used to define them.
  • Monotonic timers activate after a time span relative to a varying starting point. They stop if the computer is temporarily suspended or shut down. There are number of different monotonic timers but all have the form: On_Type_Sec=. Common monotonic timers include OnBootSec and OnUnitActiveSec.

For each .timer file, a matching .service file exists (e.g. foo.timer and foo.service). The .timer file activates and controls the .service file. The .service does not require an [Install] section as it is the timer units that are enabled. If necessary, it is possible to control a differently-named unit using the Unit= option in the timer's [Timer] section.

List timers:

systemctl list-timers

Examples

Monotonic timer

A timer which will start 15 minutes after boot and again every week while the system is running.

/etc/systemd/system/foo.timer

[Unit]
Description=Run foo weekly and on boot

[Timer]
OnBootSec=15min
OnUnitActiveSec=1w

[Install]
WantedBy=timers.target

Realtime timer

A timer which starts once a week (at 12:00am on Monday). When activated, it triggers the service immediately if it missed the last start time (option Persistent=true), for example due to the system being powered off:

/etc/systemd/system/foo.timer

[Unit]
Description=Run foo weekly

[Timer]
OnCalendar=weekly
Persistent=true

[Install]
WantedBy=timers.target

When more specific dates and times are required, OnCalendar events uses the following format:

DayOfWeek Year-Month-Day Hour:Minute:Second

An asterisk may be used to specify any value and commas may be used to list possible values. Two values separated by .. indicate a contiguous range.

In the below example the service is run the first four days of each month at 12:00 PM, but only if that day is a Monday or a Tuesday.

OnCalendar=Mon,Tue *-*-01..04 12:00:00