Difference between revisions of "Systemd/Timers"

From ArchWiki
Jump to: navigation, search
m (See also: Edited for grammar)
(Mention ranges in calendar syntax, available in systemd 231)
 
(229 intermediate revisions by 43 users not shown)
Line 2: Line 2:
 
[[Category:Daemons and system services]]
 
[[Category:Daemons and system services]]
 
[[Category:Boot process]]
 
[[Category:Boot process]]
{{Article summary start}}
+
[[fr:Systemd/cron]]
{{Article summary text|Covers how to replace cron by systemd.}}
+
[[ja:Systemd/タイマー]]
{{Article summary heading|Related}}
+
[[ru:Systemd/Timers]]
{{Article summary wiki|systemd}}
+
[[zh-CN:Systemd/Timers]]
{{Article summary wiki|systemd/User}}
+
{{Related articles start}}
{{Article summary wiki|systemd/Services}}
+
{{Related|systemd}}
{{Article summary wiki|systemd FAQ}}
+
{{Related|systemd/User}}
{{Article summary wiki|cron}}
+
{{Related|systemd FAQ}}
{{Article summary end}}
+
{{Related|cron}}
 +
{{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.
+
== Timer units ==
  
== Introduction ==
+
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:
  
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:
+
* '''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.
 +
* '''Realtime timers''' (a.k.a. wallclock timers) activate on a calendar event (like cronjobs). The option {{ic|1=OnCalendar=}} is used to define them.
  
* Last status and logging outputs can be got through journalctl. This enables proper debugging
+
For a full explanation of timer options, see the {{ic|systemd.timer(5)}}[https://www.freedesktop.org/software/systemd/man/systemd.timer.html] [[man page]]. The argument syntax for calendar events and time spans is defined on the {{ic|systemd.time(7)}}[https://www.freedesktop.org/software/systemd/man/systemd.time.html] [[man page]].
* Systemd has a lot of options which are useful for setting the environment for the job ot be done properly (eg IOSchedulingPriority, Nice or JobTimeoutSec)
+
* These jobs can be made to depend on other ''systemd'' units if required
+
  
While you do lose support for ''anacron''; ''systemd'' timer, target and service files can fill up for the rest of ''cron'' very easily.
+
== Service unit ==
  
== Hourly, daily and weekly events ==
+
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.
  
One strategy which can be used for recreating this functionality is through timers which call in targets. All services which need to be run hourly can be called in as dependencies of these targets. The strategy mentioned here has been detailed first in [http://blog.higgsboson.tk/2013/06/09/use-systemd-as-a-cron-replacement/ this blogpost].
+
== Management ==
  
{{Note|There is an AUR package {{AUR|systemd-cron}} which uses a slightly different strategy to do what is being done here. If you wish to use this package, then the following scripts might need to be modified and their locations changed for them to work properly.}}
+
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:
  
First, the creation of a few directories is required:
+
{{hc|$ 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
 +
}}
  
# mkdir /etc/systemd/system/timer-{hourly,daily,weekly}.target.wants
+
{{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.}}
  
The following files will need to be created in the paths specified in order for this to work.
+
== Example ==
  
=== Hourly events ===
+
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/timer-hourly.timer|<nowiki>
+
=== Monotonic timer ===
[Unit]
+
Description=Hourly Timer
+
  
[Timer]
+
A timer which will start 15 minutes after boot and again every week while the system is running.
OnBootSec=5min
+
OnUnitActiveSec=1h
+
Unit=timer-hourly.target
+
  
[Install]
+
{{hc|/etc/systemd/system/foo.timer|<nowiki>
WantedBy=basic.target
+
</nowiki>}}
+
 
+
{{hc|/etc/systemd/system/timer-hourly.target|<nowiki>
+
 
[Unit]
 
[Unit]
Description=Hourly Timer Target
+
Description=Run foo weekly and on boot
StopWhenUnneeded=yes
+
</nowiki>}}
+
 
+
=== Daily events ===
+
 
+
{{hc|/etc/systemd/system/timer-daily.timer|<nowiki>
+
[Unit]
+
Description=Daily Timer
+
  
 
[Timer]
 
[Timer]
OnBootSec=10min
+
OnBootSec=15min
OnUnitActiveSec=1d
+
OnUnitActiveSec=1w
Unit=timer-daily.target
+
  
 
[Install]
 
[Install]
WantedBy=basic.target
+
WantedBy=timers.target
 
</nowiki>}}
 
</nowiki>}}
  
{{hc|/etc/systemd/system/timer-daily.target|<nowiki>
+
=== Realtime timer ===
[Unit]
+
Description=Daily Timer Target
+
StopWhenUnneeded=yes
+
</nowiki>}}
+
  
=== Weekly events ===
+
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:
  
{{hc|/etc/systemd/system/timer-weekly.timer|<nowiki>
+
{{hc|/etc/systemd/system/foo.timer|<nowiki>
 
[Unit]
 
[Unit]
Description=Weekly Timer
+
Description=Run foo weekly
  
 
[Timer]
 
[Timer]
OnBootSec=15min
+
OnCalendar=weekly
OnUnitActiveSec=1w
+
Persistent=true   
Unit=timer-weekly.target
+
 
+
 
[Install]
 
[Install]
WantedBy=basic.target
+
WantedBy=timers.target</nowiki>}}
</nowiki>}}
+
  
{{hc|/etc/systemd/system/timer-weekly.target|<nowiki>
+
The format controlling {{ic|OnCalendar}} events uses the following format when more specific dates and times are required: {{ic|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 {{ic|..}} may be used to indicate a contiguous range. In this example the service is run the first four days of each month at 12:00 PM, but ''only'' if that day is also on a Monday or a Tuesday. More information is available in {{ic|man systemd.time}}.
[Unit]
+
Description=Weekly Timer Target
+
StopWhenUnneeded=yes
+
</nowiki>}}
+
  
=== Adding events ===
+
OnCalendar=Mon,Tue *-*-01..04 12:00:00
  
Adding events to these targets is as easy as dropping them into the correct ''wants'' folder. So if you wish for a particular job to take place daily, create a systemd service file and drop it into the relevant folder.
+
{{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)}}.}}
  
For example, if you wish to run {{ic|foo.service}} daily (which runs program bar), you would create the following file:
+
== Transient .timer units ==
  
{{hc|/etc/systemd/system/timer-daily.target.wants/foo.service|<nowiki>
+
One can use {{ic|systemd-run}} to create transient {{ic|.timer}} units. That is, one can set a command to run at a specified time without having a service file. For example the following command touches a file after 30 seconds:
[Unit]
+
Description=Starts program bar
+
  
[Service]
+
# systemd-run --on-active=30 /bin/touch /tmp/foo
User=                                          # Add a user if you wish the service to be executes as a particular user, else delete this line
+
Type=                                          # Simple by default, change it if you know what you are doing, else delete this line
+
Nice=19
+
IOSchedulingClass=2
+
IOSchedulingPriority=7
+
ExecStart=/usr/bin/bar --option1 --option2    # More than one ExecStart can be used if required
+
</nowiki>}}
+
  
=== Some important default Arch Linux cronjobs ===
+
One can also specify a pre-existing service file that does not have a timer file. For example, the following starts the systemd unit named {{ic|''someunit''.service}} after 12.5 hours have elapsed:
  
If you wish to completely migrate away from ''cron'' to ''systemd'', then it is prudent to have these services up and running for your system to remain workable.
+
# systemd-run --on-active="12h 30m" --unit ''someunit''.service
  
==== Logrotate ====
+
See {{ic|man systemd-run}} for more information and examples.
  
{{hc|/etc/systemd/system/timer-daily.target.wants/logrotate.service|<nowiki>
+
== As a cron replacement ==
[Unit]
+
Description=Rotate Logs
+
  
[Service]
+
Although [[cron]] is arguably the most well-known job scheduler, ''systemd'' timers can be an alternative.
Nice=19
+
IOSchedulingClass=2
+
IOSchedulingPriority=7
+
ExecStart=/usr/bin/logrotate /etc/logrotate.conf
+
</nowiki>}}
+
  
==== Update man-db ====
+
=== Benefits ===
  
{{hc|/etc/systemd/system/timer-daily.target.wants/man-db-update.service|<nowiki>
+
The main benefits of using timers come from each job having its own ''systemd'' service. Some of these benefits are:
[Unit]
+
Description=Update man-db
+
  
[Service]
+
* Jobs can be easily started independently of their timers. This simplifies debugging.
Nice=19
+
* Each job can be configured to run in a specific environment (see the {{ic|systemd.exec(5)}} [[man page]]).
IOSchedulingClass=2
+
* Jobs can be attached to [[cgroups]].
IOSchedulingPriority=7
+
* Jobs can be set up to depend on other ''systemd'' units.
ExecStart=/usr/bin/mandb --quiet
+
* Jobs are logged in the ''systemd'' journal for easy debugging.
</nowiki>}}
+
  
==== Update mlocate database ====
+
=== Caveats ===
  
{{hc|/etc/systemd/system/timer-daily.target.wants/mlocate-update.service|<nowiki>
+
Some things that are easy to do with cron are difficult to do with timer units alone.
[Unit]
+
Description=Update mlocate database
+
  
[Service]
+
* 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.
Nice=19
+
* 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=}}.
IOSchedulingClass=2
+
IOSchedulingPriority=7
+
ExecStart=/usr/bin/updatedb
+
</nowiki>}}
+
  
==== Verify integrity of password and group files ====
+
=== MAILTO ===
  
{{hc|/etc/systemd/system/timer-daily.target.wants/verify-shadow.service|<nowiki>
+
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}}:
[Unit]
+
Description=Verify integrity of password and group files
+
  
[Service]
+
{{hc|/usr/local/bin/systemd-email|<nowiki>#!/bin/bash
Type=oneshot
+
ExecStart=/usr/bin/pwck -r
+
ExecStart=/usr/bin/grpck -r
+
</nowiki>}}
+
  
=== Enable and start the timers ===
+
/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 enable timer-{hourly,daily,weekly}.timer && systemctl start timer-{hourly,daily,weekly}.timer
+
$(systemctl status --full "$2")
 +
ERRMAIL</nowiki>}}
  
== Starting events according to the calendar ==
+
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:
  
If you wish to start a service according to a calendar event and not a monotonic interval (i.e. you wish to replace the functionality of crontab), you will need to create a new timer and link your service file to that. An example would be:
+
{{hc|/etc/systemd/system/status-email-''user''@.service|2=[Unit]
 
+
Description=status email for %I to ''user''
{{hc|/etc/systemd/system/foo.timer|<nowiki>
+
[Unit]
+
Description=foo timer
+
 
+
[Timer]
+
OnCalendar=Mon-Thu *-9-28 *:30:00 # To add a time of your choosing here, please refer to systemd.time manual page for the correct format
+
Unit=foo.service
+
 
+
[Install]
+
WantedBy=basic.target
+
</nowiki>}}
+
 
+
The service file may be created the same way as the events for monotonic clocks. However, take care to put them in the {{ic|/etc/systemd/system/}} folder.
+
 
+
== Custom/example service files ==
+
 
+
{{Note|These example scripts assume that you have created the hourly, daily and weekly timers as described above.}}
+
 
+
=== The pkgstats service ===
+
 
+
If you have the {{Pkg|pkgstats}} package installed, this service will be necessary in order to send data back to the Arch servers.
+
 
+
{{Tip|It should be noted that the user {{ic|nobody}}, which is being used here, is already present on all Arch systems. The use of this user is recommended for all services which can function in a completely unprivileged environment.}}
+
 
+
{{hc|/etc/systemd/system/timer-weekly.target.wants/pkgstats.service|<nowiki>
+
[Unit]
+
Description=Run pkgstats
+
  
 
[Service]
 
[Service]
 +
Type=oneshot
 +
ExecStart=/usr/local/bin/systemd-email ''address'' %i
 
User=nobody
 
User=nobody
ExecStart=/usr/bin/pkgstats
+
Group=systemd-journal}}
</nowiki>}}
+
  
=== The modprobed_db service ===
+
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.
  
This service is of great use to people who compile their own kernels because it reduces compilation time by a significant amount. Refer to the [[Modprobed_db]] page for further details.
+
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.
  
{{hc|/etc/systemd/system/timer-daily.target.wants/modprobed_db.service|<nowiki>
+
{{note|
[Unit]
+
* 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.
Description=Run modprobed_db
+
* 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''}}.}}
  
[Service]
+
=== Using a crontab ===
User=</nowiki>''enter user here''<nowiki>
+
ExecStart=/usr/bin/modprobed_db store
+
</nowiki>}}
+
  
=== The reflector service ===
+
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 service file may be used to upgrade the mirrorlist daily using the [[Reflector]] program.
+
If you like crontabs just because they provide a unified view of all scheduled jobs, {{ic|systemctl}} can provide this. See [[#Management]].
 
+
{{hc|/etc/systemd/system/timer-daily.target.wants/reflector.service|<nowiki>
+
[Unit]
+
Description=Update the mirrorlist
+
 
+
[Service]
+
Nice=19
+
IOSchedulingClass=2
+
IOSchedulingPriority=7
+
ExecStart=/usr/bin/reflector --protocol http --latest 30 --number 20 --sort rate --save /etc/pacman.d/mirrorlist
+
</nowiki>}}
+
 
+
=== The man-db service ===
+
 
+
This service runs ''mandb'', which updates the manual page index caches. See {{ic|man 8 mandb}} for details. The package {{Pkg|man-db}} provides a cron job for this task (file {{ic|/etc/cron.daily/man-db}}).
+
 
+
{{hc|/etc/systemd/system/timer-daily.target.wants/man-db.service|<nowiki>
+
[Unit]
+
Description=Update manual page index caches
+
 
+
[Service]
+
Nice=19
+
IOSchedulingClass=2
+
IOSchedulingPriority=7
+
ExecStart=/usr/bin/mandb --quiet
+
</nowiki>}}
+
 
+
=== The shadow service ===
+
 
+
This service verifies integrity of password and group files ({{ic|/etc/{passwd,shadow,group,gshadow} }}). The package {{Pkg|shadow}} provides a cron job for this task (file {{ic|/etc/cron.daily/shadow}}).
+
 
+
{{hc|/etc/systemd/system/timer-daily.target.wants/shadow.service|<nowiki>
+
[Unit]
+
Description=Verify integrity of password and group files
+
 
+
[Service]
+
Type=oneshot
+
ExecStart=/usr/bin/pwck -r
+
ExecStart=/usr/bin/grpck -r
+
</nowiki>}}
+
  
 
== 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/systemd-cron/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 01:22, 23 August 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)[1] man page. The argument syntax for calendar events and time spans is defined on the systemd.time(7)[2] 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

The format controlling OnCalendar events uses the following format when more specific dates and times are required: 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 .. may be used to indicate a contiguous range. In this example the service is run the first four days of each month at 12:00 PM, but only if that day is also on a Monday or a Tuesday. More information is available in man systemd.time.

OnCalendar=Mon,Tue *-*-01..04 12:00:00
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).

Transient .timer units

One can use systemd-run to create transient .timer units. That is, one can set a command to run at a specified time without having a service file. For example the following command touches a file after 30 seconds:

# systemd-run --on-active=30 /bin/touch /tmp/foo

One can also specify a pre-existing service file that does not have a timer file. For example, the following starts the systemd unit named someunit.service after 12.5 hours have elapsed:

# systemd-run --on-active="12h 30m" --unit someunit.service

See man systemd-run for more information and examples.

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/systemd-cron/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