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

62 lines
2.4 KiB
Markdown
Raw Normal View History

2023-12-04 10:02:23 +00:00
---
obj: concept
2023-12-10 00:57:29 +00:00
arch-wiki: https://wiki.archlinux.org/title/Systemd/Timers
2023-12-04 10:02:23 +00:00
---
# Systemd Timers
2024-01-17 08:44:04 +00:00
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:
2023-12-04 10:02:23 +00:00
2024-01-17 08:44:04 +00:00
- **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`.
2023-12-04 10:02:23 +00:00
2024-01-17 08:44:04 +00:00
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.
2023-12-04 10:02:23 +00:00
List timers:
```shell
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
2024-01-17 08:44:04 +00:00
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:
2023-12-04 10:02:23 +00:00
`/etc/systemd/system/foo.timer`
```
[Unit]
Description=Run foo weekly
[Timer]
OnCalendar=weekly
Persistent=true
[Install]
WantedBy=timers.target
```
2024-01-17 08:44:04 +00:00
When more specific dates and times are required, `OnCalendar` events uses the following format:
2023-12-04 10:02:23 +00:00
`DayOfWeek Year-Month-Day Hour:Minute:Second`
2024-01-17 08:44:04 +00:00
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.
2023-12-04 10:02:23 +00:00
2024-01-17 08:44:04 +00:00
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.
2023-12-04 10:02:23 +00:00
`OnCalendar=Mon,Tue *-*-01..04 12:00:00`