Difference between revisions of "Systemd/Timers"

From ArchWiki
Jump to: navigation, search
m (Run On Intervals: add tip to avoid too many services at 00:00:00)
(MAILTO: simpler/more consistent uses of pseudovariables)
 
(126 intermediate revisions by 27 users not shown)
Line 3: Line 3:
 
[[Category:Boot process]]
 
[[Category:Boot process]]
 
[[fr:Systemd/cron]]
 
[[fr:Systemd/cron]]
[[ja:Systemd/cron functionality]]
+
[[ja:Systemd/タイマー]]
 +
[[ru:Systemd/Timers]]
 +
[[zh-CN:Systemd/Timers]]
 
{{Related articles start}}
 
{{Related articles start}}
 
{{Related|systemd}}
 
{{Related|systemd}}
 
{{Related|systemd/User}}
 
{{Related|systemd/User}}
{{Related|systemd/Services}}
 
 
{{Related|systemd FAQ}}
 
{{Related|systemd FAQ}}
 
{{Related|cron}}
 
{{Related|cron}}
 
{{Related articles end}}
 
{{Related articles end}}
 +
Timers are [[systemd]] unit files whose name ends in {{ic|.timer}} that control {{ic|.service}} files or events.  Timers can be used as an alternative to [[cron]] (read [[#As a cron replacement]]).  Timers have built-in support for calendar time events, monotonic time events, and can be run asynchronously.
  
[[Systemd]] is capable of taking on a significant subset of the functionality of [[Cron]] through built in support for calendar time events (from systemd version 197) as well as monotonic time events. As of systemd version 212, it also has the foundations for being an anacron replacement through the use of the {{ic|Persistent}} and {{ic|OnCalendar}} options in timers.
+
== Timer units ==
  
While Cron has been a stalwart on the Linux landscape for years, it still provides no way to detect job failures, establish job dependencies, or allocate processes to cgroups. If you require any of this functionality, ''systemd'' provides a good structure to set up job scheduling. While doing so is slightly more cumbersome than relying on ''dcron'' or ''cronie'', the benefits are not insignificant:
+
Timers are ''systemd'' unit files with a suffix of {{ic|.timer}}. Timers are like other [[systemd#Writing unit files|unit configuration files]] and are loaded from the same paths but include a {{ic|[Timer]}} section.  The {{ic|[Timer]}} section defines when and how the timer activates. Timers are defined as one of two types:
  
* Status and logging outputs can be got through journalctl. This enables proper debugging.
+
* '''Monotonic timers''' activate after a time span relative to a varying starting point. There are number of different monotonic timers but all have the form of: {{ic|1=On''Type''Sec=}}.  {{ic|OnBootSec}} and {{ic|OnActiveSec}} are common monotonic timers.
* Jobs are decoupled from their timers. This allows jobs to be easily run independently of their timers or for multiple timers to trigger a single job.
+
* '''Realtime timers''' (a.k.a. wallclock timers) activate on a calendar event (like cronjobs). The option {{ic|1=OnCalendar=}} is used to define them.
* Each job can be configured to run in a specific environment (see {{ic|systemd.exec(5)}}).
+
* Jobs can be made to depend on other systemd units.
+
  
== Timer units ==
+
For a full explanation of timer options, see the {{ic|systemd.timer(5)}} [[man page]]. The argument syntax for calendar events and time spans is defined on the {{ic|systemd.time(7)}} [[man page]].
  
These files are systemd unit files with name ending in ''.timer''. Writing these files follows the common options of all unit configuration files. Please refer to [[systemd#Writing custom .service files]] for a quick look at the overall syntax.
+
== Service unit ==
  
The timer specific configuration options are configured in a {{ic|[Timer]}} section. There are two ways to define when the timed service will be triggered:
+
For each {{ic|.timer}} file, a matching {{ic|.service}} file exists (e.g. {{ic|foo.timer}} and {{ic|foo.service}}).  The {{ic|.timer}} file activates and controls the {{ic|.service}} file.  The {{ic|.service}} does not require an {{ic|[Install]}} section as it is the ''timer'' units that are enabled.  If necessary, it is possible to control a differently-named unit using the {{ic|1=Unit=}} option in the timer's {{ic|[Timer]}} section.
  
* time relative to a ''starting point'' such as the last boot (using {{ic|OnBootSec}}) or the time the service was last activated (using {{ic|OnUnitActiveSec}}).
+
== Management ==
* time relative to a ''real time'' (using {{ic|OnCalendar}}).
+
  
For each timer file, a matching unit service file must exist, describing the unit to activate when the timer elapses. By default, this will be a service by the same name as the timer (except for the suffix). For example, {{ic|foo.timer}} will activate and control {{ic|foo.service}}. As the service will be started by the timer, the service does not need an {{ic|[Install]}} section. Instead, you should specify {{ic|1=WantedBy=timers.target}} in the timer's {{ic|[Install]}} section and enable the timer unit. See {{ic|systemd.timer(5)}} for a full list of options available for timer units.
+
To use a ''timer'' unit [[enable]] and [[start]] it like any other unit (remember to add the {{ic|.timer}} suffix). To view all started timers, run:
 
+
To see all of your active timers with time details, run:
+
  
 
{{hc|$ systemctl list-timers|
 
{{hc|$ systemctl list-timers|
Line 39: Line 36:
 
Fri 2014-07-11 00:00:00 CEST  15h left    Thu 2014-07-10 00:00:13 CEST  8h ago    logrotate.timer              logrotate.service
 
Fri 2014-07-11 00:00:00 CEST  15h left    Thu 2014-07-10 00:00:13 CEST  8h ago    logrotate.timer              logrotate.service
 
}}
 
}}
 +
 +
{{Note|
 +
* To list all timers (including inactive), use {{ic|systemctl list-timers --all}}.
 +
* The status of a service started by a timer will likely be inactive unless it is currently being triggered.
 +
* If a timer gets out of sync, it may help to delete its {{ic|stamp-*}} file in {{ic|/var/lib/systemd/timers}}. These are zero length files which mark the last time each timer was run. If deleted, they will be reconstructed on the next start of their timer.}}
  
 
== Example ==
 
== Example ==
  
Every scheduled task requires its own service file. Our example is a backup script which we will set up to run weekly.
+
No changes to service unit files are needed to schedule them with a timer. The following example schedules {{ic|foo.service}} to be run with a corresponding timer called {{ic|foo.timer}}.  
  
{{hc|/etc/systemd/system/myBackup.service|<nowiki>
+
=== Monotonic timer ===
[Unit]
+
Description=full system backup
+
  
[Service]
+
A timer which will start 15 minutes after boot and again every week while the system is running.
Nice=19
+
IOSchedulingClass=2
+
IOSchedulingPriority=7
+
ExecStart=/path/to/myBackup/script 
+
</nowiki>}}
+
 
+
There are a couple ways you could make a timer for this service, but the timer ''must'' have the same name as the service (i.e. {{ic|myBackup.timer}}) or specify {{ic|Unit&#61;myBackup.service}}.
+
 
+
=== Run On Intervals ===
+
 
+
If you wish to run backups according to a calendar event, use the {{ic|OnCalendar}} option.
+
  
{{hc|/etc/systemd/system/myBackup.timer|<nowiki>
+
{{hc|/etc/systemd/system/foo.timer|<nowiki>
 
[Unit]
 
[Unit]
Description=weekly full backup
+
Description=Run foo weekly and on boot
  
 
[Timer]
 
[Timer]
OnCalendar=weekly # see systemd.time(7) manual page for other scheduling options
+
OnBootSec=15min
AccuracySec=1h    # allow flexibility in start time
+
OnUnitActiveSec=1w
Persistent=true  # run immediately if we missed a backup for some reason
+
  
 
[Install]
 
[Install]
Line 74: Line 62:
 
</nowiki>}}
 
</nowiki>}}
  
{{Tip|Using OnCalendar &#61; weekly, as described above, will trigger the service once in a week at 00:00:00. In case you run many heavy services, best would be to trigger part of them in another time than 00:00:00. As an example, you can write such calendar event: {{ic|OnCalendar &#61; Wed *-*-* 23:15:00}}. In that way, your service will be triggered each Wednesday at 23:15:00
+
=== Realtime timer ===
}}
+
  
=== Run After Booting ===
+
A timer which starts once a week (at 12:00am on Monday). It starts once immediately if it missed the last start time (option {{ic|1=Persistent=true}}), for example due to the system being powered off:
  
Alternatively, if you want to run backups every time the system boots (and every week while between reboots), you can combine {{ic|OnBootSec}} with {{ic|OnUnitActiveSec}}.
+
{{hc|/etc/systemd/system/foo.timer|<nowiki>
 
+
{{hc|/etc/systemd/system/myBackup.timer|<nowiki>
+
 
[Unit]
 
[Unit]
Description=weekly and post-boot backup
+
Description=Run foo weekly
  
 
[Timer]
 
[Timer]
OnBootSec=15min    # run 15 minutes after boot time
+
OnCalendar=weekly
OnUnitActiveSec=1w # run 1 week after service was last started
+
Persistent=true   
AccuracySec=10min
+
 
+
 
[Install]
 
[Install]
WantedBy=timers.target
+
WantedBy=timers.target</nowiki>}}
</nowiki>}}
+
  
{{Note|In case of resource-eating services, do not set the timer too close to boot. It could seriously delay your login and X sessions.}}
+
{{Tip|Special event expressions like {{ic|daily}} and {{ic|weekly}} refer to ''specific start times'' and thus any timers sharing such calendar events will start simultaneously. Timers sharing start events can cause poor system performance if the timers' services compete for system resources.  The {{ic|RandomizedDelaySec}} option avoids this problem by randomly staggering the start time of each timer. See {{ic|systemd.timer (5)}}.}}
  
=== Management ===
+
== As a cron replacement ==
  
You do not need to enable or start the service file yourself, simply [[Systemd | enable and start]] the timer. To double check that your new timer and service are enabled, run the following commands:
+
Although [[cron]] is arguably the most well-known job scheduler, ''systemd'' timers can be an alternative.
  
{{hc|$ systemctl status myBackup|<nowiki>
+
=== Benefits ===
● myBackup.service - full system backup
+
  Loaded: loaded (/etc/systemd/system/myBackup.service; static)
+
  Active: inactive (dead) since Wed 2014-07-09 10:27:45 CEST; 1h 8min ago
+
Main PID: 22000 (code=exited, status=0/SUCCESS)
+
  
Jul 09 10:27:45 host systemd[1]: Started full system backup.
+
The main benefits of using timers come from each job having its own ''systemd'' service. Some of these benefits are:
</nowiki>}}
+
  
{{hc|$ systemctl status myBackup.timer|<nowiki>
+
* Jobs can be easily started independently of their timers. This simplifies debugging.
● myBackup.timer - weekly and post-boot backup
+
* Each job can be configured to run in a specific environment (see the {{ic|systemd.exec(5)}} [[man page]]).
  Loaded: loaded (/etc/systemd/system/myBackup.timer; enabled)
+
* Jobs can be attached to [[cgroups]].
  Active: active (waiting) since Mon 2014-07-07 19:21:53 CEST; 1 day 16h ago
+
* Jobs can be set up to depend on other ''systemd'' units.
 +
* Jobs are logged in the ''systemd'' journal for easy debugging.
  
Jul 07 19:21:53 host systemd[1]: Starting weekly and post-boot backup.
+
=== Caveats ===
Jul 07 19:21:53 host systemd[1]: Started weekly and post-boot backup.
+
</nowiki>}}
+
  
{{Note|
+
Some things that are easy to do with cron are difficult to do with timer units alone.
* The service is marked as ''inactive'' since its status indicates whether the backup (not the timer) is ''currently running''
+
 
* The timer is marked as ''waiting'' as it is waiting for the next trigger to start the backup
+
* Complexity: to set up a timed job with ''systemd'' you create two files and run a couple {{ic|systemctl}} commands. Compare that to adding a single line to a crontab.
}}
+
* Emails: there is no built-in equivalent to cron's {{ic|MAILTO}} for sending emails on job failure. See the next section for an example of setting up an equivalent using {{ic|1=OnFailure=}}.
 +
 
 +
=== MAILTO ===
 +
 
 +
You can set up systemd to send an e-mail when a unit fails - much like Cron does with {{ic|MAILTO}}. First you need two files: an executable for sending the mail and a ''.service'' for starting the executable. For this example, the executable is just a shell script using {{ic|sendmail}}:
 +
 
 +
{{hc|/usr/local/bin/systemd-email|<nowiki>#!/bin/bash
 +
 
 +
/usr/bin/sendmail -t <<ERRMAIL
 +
To: $1
 +
From: systemd <root@$HOSTNAME>
 +
Subject: $2
 +
Content-Transfer-Encoding: 8bit
 +
Content-Type: text/plain; charset=UTF-8
 +
 
 +
$(systemctl status --full "$2")
 +
ERRMAIL</nowiki>}}
 +
 
 +
Whatever executable you use, it should probably take at least two arguments as this shell script does: the address to send to and the unit file to get the status of. The ''.service'' we create will pass these arguments:
 +
 
 +
{{hc|/etc/systemd/system/status-email-''user''@.service|2=[Unit]
 +
Description=status email for %I to ''user''
 +
 
 +
[Service]
 +
Type=oneshot
 +
ExecStart=/usr/local/bin/systemd-email ''address'' %i
 +
User=nobody
 +
Group=systemd-journal}}
 +
 
 +
Where {{ic|''user''}} is the user being emailed and {{ic|''address''}} is that user's email address. Although the recipient is hard-coded, the unit file to report on is passed as an instance parameter, so this one service can send email for many other units. At this point you can [[start]] {{ic|status-email-''user''@dbus.service}} to verify that you can receive the emails.
 +
 
 +
Then simply [[systemd#Editing provided units|edit]] the service you want emails for and add {{ic|1=OnFailure=status-email-''user''@%n.service}} to the {{ic|[Unit]}} section. {{ic|%n}} passes the unit's name to the template.
 +
 
 +
{{note|
 +
* If you set up SSMTP security according to [[SSMTP#Security]] the user {{ic|nobody}} will not have access to {{ic|/etc/ssmtp/ssmtp.conf}}, and the {{ic|systemctl start status-email-''user''@dbus.service}} command will fail. One solution is to use {{ic|root}} as the User in the {{ic|status-email-''user''@.service}} unit.
 +
* If you try to use {{ic|mail -s somelogs ''address''}} in your email script, {{ic|mail}} will fork and systemd will kill the mail process when it sees your script exit. Make the mail non-forking by doing {{ic|mail -Ssendwait -s somelogs ''address''}}.}}
 +
 
 +
=== Using a crontab ===
  
== Caveats ==
+
Several of the caveats can be worked around by installing a package that parses a traditional crontab to configure the timers. {{AUR|systemd-cron-next}} and {{AUR|systemd-cron}} are two such packages. These can provide the missing {{ic|MAILTO}} feature.
This describes a few caveats involved when migrating from cron jobs to systemd timer units.
+
  
=== Parallelization ===
+
If you like crontabs just because they provide a unified view of all scheduled jobs, {{ic|systemctl}} can provide this. See [[#Management]].
Currently, there is no built-in way to spread timers out evenly across a given interval. While {{ic|AccuracySec}} is sometimes offered as a solution, the randomization it implies is designed such that it is synchronised between all local timer units, and is not equivalent to cron’s random delay configuration. E.g., all daily timer units with {{ic|1=AccuracySec=15m}} will trigger the associated jobs at the same point in time between 00:00 and 00:15.
+
  
 
== See also ==
 
== See also ==
  
* https://fedoraproject.org/wiki/Features/SystemdCalendarTimers - systemd calendar timers on the Fedora Project wiki
+
* [http://www.freedesktop.org/software/systemd/man/systemd.timer.html systemd.timer man page] on freedesktop.org
 +
* [https://fedoraproject.org/wiki/Features/SystemdCalendarTimers Fedora Project wiki page] on ''systemd'' calendar timers
 +
* [https://wiki.gentoo.org/wiki/Systemd#Timer_services Gentoo wiki section] on ''systemd'' timer services
 +
* {{App|systemd-cron-next|tool to generate timers/services from crontab and anacrontab files|https://github.com/kstep/systemd-cron-next|{{Aur|systemd-cron-next}}}}
 +
* {{App|systemd-cron|provides systemd units to run cron scripts; using ''systemd-crontab-generator'' to convert crontabs|https://github.com/systemd-cron/systemd-cron|{{Aur|systemd-cron}}}}

Latest revision as of 23:21, 5 April 2016

Timers are systemd unit files whose name ends in .timer that control .service files or events. Timers can be used as an alternative to cron (read #As a cron replacement). Timers have built-in support for calendar time events, monotonic time events, and can be run asynchronously.

Timer units

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. The [Timer] section defines when and how the timer activates. Timers are defined as one of two types:

  • Monotonic timers activate after a time span relative to a varying starting point. There are number of different monotonic timers but all have the form of: OnTypeSec=. OnBootSec and OnActiveSec are common monotonic timers.
  • Realtime timers (a.k.a. wallclock timers) activate on a calendar event (like cronjobs). The option OnCalendar= is used to define them.

For a full explanation of timer options, see the systemd.timer(5) man page. The argument syntax for calendar events and time spans is defined on the systemd.time(7) man page.

Service unit

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.

Management

To use a timer unit enable and start it like any other unit (remember to add the .timer suffix). To view all started timers, run:

$ systemctl list-timers
NEXT                          LEFT        LAST                          PASSED     UNIT                         ACTIVATES
Thu 2014-07-10 19:37:03 CEST  11h left    Wed 2014-07-09 19:37:03 CEST  12h ago    systemd-tmpfiles-clean.timer systemd-tmpfiles-clean.service
Fri 2014-07-11 00:00:00 CEST  15h left    Thu 2014-07-10 00:00:13 CEST  8h ago     logrotate.timer              logrotate.service
Note:
  • To list all timers (including inactive), use systemctl list-timers --all.
  • The status of a service started by a timer will likely be inactive unless it is currently being triggered.
  • If a timer gets out of sync, it may help to delete its stamp-* file in /var/lib/systemd/timers. These are zero length files which mark the last time each timer was run. If deleted, they will be reconstructed on the next start of their timer.

Example

No changes to service unit files are needed to schedule them with a timer. The following example schedules foo.service to be run with a corresponding timer called foo.timer.

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). It starts once 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
Tip: Special event expressions like daily and weekly refer to specific start times and thus any timers sharing such calendar events will start simultaneously. Timers sharing start events can cause poor system performance if the timers' services compete for system resources. The RandomizedDelaySec option avoids this problem by randomly staggering the start time of each timer. See systemd.timer (5).

As a cron replacement

Although cron is arguably the most well-known job scheduler, systemd timers can be an alternative.

Benefits

The main benefits of using timers come from each job having its own systemd service. Some of these benefits are:

  • Jobs can be easily started independently of their timers. This simplifies debugging.
  • Each job can be configured to run in a specific environment (see the systemd.exec(5) man page).
  • Jobs can be attached to cgroups.
  • Jobs can be set up to depend on other systemd units.
  • Jobs are logged in the systemd journal for easy debugging.

Caveats

Some things that are easy to do with cron are difficult to do with timer units alone.

  • Complexity: to set up a timed job with systemd you create two files and run a couple systemctl commands. Compare that to adding a single line to a crontab.
  • Emails: there is no built-in equivalent to cron's MAILTO for sending emails on job failure. See the next section for an example of setting up an equivalent using OnFailure=.

MAILTO

You can set up systemd to send an e-mail when a unit fails - much like Cron does with MAILTO. First you need two files: an executable for sending the mail and a .service for starting the executable. For this example, the executable is just a shell script using sendmail:

/usr/local/bin/systemd-email
#!/bin/bash

/usr/bin/sendmail -t <<ERRMAIL
To: $1
From: systemd <root@$HOSTNAME>
Subject: $2
Content-Transfer-Encoding: 8bit
Content-Type: text/plain; charset=UTF-8

$(systemctl status --full "$2")
ERRMAIL

Whatever executable you use, it should probably take at least two arguments as this shell script does: the address to send to and the unit file to get the status of. The .service we create will pass these arguments:

/etc/systemd/system/status-email-user@.service
[Unit]
Description=status email for %I to user

[Service]
Type=oneshot
ExecStart=/usr/local/bin/systemd-email address %i
User=nobody
Group=systemd-journal

Where user is the user being emailed and address is that user's email address. Although the recipient is hard-coded, the unit file to report on is passed as an instance parameter, so this one service can send email for many other units. At this point you can start status-email-user@dbus.service to verify that you can receive the emails.

Then simply edit the service you want emails for and add OnFailure=status-email-user@%n.service to the [Unit] section. %n passes the unit's name to the template.

Note:
  • If you set up SSMTP security according to SSMTP#Security the user nobody will not have access to /etc/ssmtp/ssmtp.conf, and the systemctl start status-email-user@dbus.service command will fail. One solution is to use root as the User in the status-email-user@.service unit.
  • If you try to use mail -s somelogs address in your email script, mail will fork and systemd will kill the mail process when it sees your script exit. Make the mail non-forking by doing mail -Ssendwait -s somelogs address.

Using a crontab

Several of the caveats can be worked around by installing a package that parses a traditional crontab to configure the timers. systemd-cron-nextAUR and systemd-cronAUR are two such packages. These can provide the missing MAILTO feature.

If you like crontabs just because they provide a unified view of all scheduled jobs, systemctl can provide this. See #Management.

See also

https://github.com/kstep/systemd-cron-next || systemd-cron-nextAUR
  • systemd-cron — provides systemd units to run cron scripts; using systemd-crontab-generator to convert crontabs
https://github.com/systemd-cron/systemd-cron || systemd-cronAUR