用于调度任务的 systemd 定时器
定时器 cron
![](/data/attachment/album/202106/25/175650j4wrdw0z884iod80.jpg)


systemd 提供定时器有一段时间了，定时器替代了 cron 功能，这一特性值得看看。本文将向你介绍在系统启动后如何使用 systemd 中的定时器来运行任务，并在此后重复运行。这不是对 systemd 的全面讨论，只是对此特性的一个介绍。


### 快速回顾：cron、anacron 与 systemd


cron 可以以几分钟到几个月或更长时间的粒度调度运行一个任务。设置起来相对简单，它只需要一个配置文件。虽然配置过程有些深奥，但一般用户也可以使用。


然而，如果你的系统在需要执行的时间没有运行，那么 cron 会失败。


anacron 克服了“系统没有运行”的问题。它确保任务将在你的系统再次启动时执行。虽然它旨在给管理员使用，但有些系统允许普通用户访问 anacron。


但是，anacron 的执行频率不能低于每天一次。


cron 和 anacron 都存在执行上下文一致性的问题。必须注意任务运行时有效的环境与测试时使用的环境完全相同。必须提供相同的 shell、环境变量和路径。这意味着测试和调试有时会很困难。


systemd 定时器提供了 cron 和 anacron 二者的优点，允许调度到分钟粒度。确保在系统再次运行时执行任务，即使在预期的执行时间内系统处于关闭状态。它对所有用户都可用。你可以在它将要运行的环境中测试和调试执行。


但是，它的配置更加复杂，至少需要两个配置文件。


如果你的 cron 和 anacron 配置可以很好地为你服务，那么可能没有理由改变。但是 systemd 至少值得研究，因为它可以简化任何当前的 cron/anacron 工作方式。


### 配置


systemd 定时器执行功能至少需要两个文件。这两个是“<ruby> 定时器单元 <rt>  timer unit </rt></ruby>”和“<ruby> 服务单元 <rt>  service unit </rt></ruby>”。（其执行的）“动作”不仅仅是简单的命令，你还需要一个“作业”文件或脚本来执行必要的功能。


定时器单元文件定义调度表，而服务单元文件定义执行的任务。有关的更多详细信息请参考 `man systemd.timer` 中提供的 .timer 单元。服务单元的详细信息可在 `man systemd.service` 中找到。


单元文件存放在几个位置（在手册页中有列出）。然而，对于普通用户来说，最容易找到的位置可能是 `~/.config/systemd/user`。请注意，这里的 `user` 是字符串 `user`。


### 示例


此示例是一个创建用户调度作业而不是（以 root 用户身份运行的）系统调度作业的简单示例。它将消息、日期和时间打印到文件中。


1、首先创建一个执行任务的 shell 脚本。在你的本地 `bin` 目录中创建它，例如在 `~/bin/schedule-test.sh` 中。


创建文件：



```
touch ~/bin/schedule-test.sh

```

然后将以下内容添加到你刚刚创建的文件中：



```
#!/bin/sh
echo "This is only a test: $(date)" >> "$HOME/schedule-test-output.txt"

```

记住赋予你的 shell 脚本执行权限。


2、创建 .service 单元调用上面的脚本。在以下位置创建目录与文件：`~/.config/systemd/user/schedule-test.service`：



```
[Unit]
Description=A job to test the systemd scheduler

[Service]
Type=simple
ExecStart=/home/<user>/bin/schedule-test.sh

[Install]
WantedBy=default.target

```

请注意 `<user>` 应该是你的家目录地址，但是单元文件路径名中的 `user` 实际上是字符串 `user`。


`ExecStart` 应该提供一个没有变量的绝对地址。例外情况是，对于用户单元文件，你可以用 `%h` 替换 `$HOME`。换句话说，你可以使用:



```
ExecStart=%h/bin/schedule-test.sh

```

这仅用于用户单元文件，而不适用于系统服务，因为在系统环境中运行时 `%h` 总是返回 `/root`。其他特殊符号可在 `man systemd.unit` 的 `SPECIFIERS` 中找到。因为它超出了本文的范围，所以这就是我们目前需要了解的关于特殊符号的全部内容。


3、创建一个 .timer 单元文件，该文件实际上调度你创建的 .service 单元文件。在 .service 单元文件相同位置创建它：`~/.config/systemd/user/schedule-test.timer`。请注意，文件名仅在扩展名上有所不同，例如一个是 `.service`，一个是 `.timer`。



```
[Unit]
Description=Schedule a message every 1 minute
RefuseManualStart=no  # Allow manual starts
RefuseManualStop=no   # Allow manual stops

[Timer]
#Execute job if it missed a run due to machine being off
Persistent=true
#Run 120 seconds after boot for the first time
OnBootSec=120
#Run every 1 minute thereafter
OnUnitActiveSec=60
#File describing job to execute
Unit=schedule-test.service

[Install]
WantedBy=timers.target

```

请注意，这个 .timer 单元文件使用了 `OnUnitActiveSec` 来指定调度表。`OnCalendar` 选项更加灵活。例如:



```
# run on the minute of every minute every hour of every day
 OnCalendar=*-*-* *:*:00
# run on the hour of every hour of every day
 OnCalendar=*-*-* *:00:00
# run every day
 OnCalendar=*-*-* 00:00:00
# run 11:12:13 of the first or fifth day of any month of the year
# 2012, but only if that day is a Thursday or Friday
 OnCalendar=Thu,Fri 2012-*-1,5 11:12:13

```

有关 `OnCalendar` 的更多信息参见 [这里](https://www.freedesktop.org/software/systemd/man/systemd.time.html#Calendar%20Events)。


4、所有的部件都已就位，但你应该进行测试，以确保一切正常。首先，启用该用户服务:



```
$ systemctl --user enable schedule-test.service

```

这将导致类似如下的输出:



```
Created symlink /home/<user>/.config/systemd/user/default.target.wants/schedule-test.service → /home/<user>/.config/systemd/user/schedule-test.service.

```

现在执行测试工作：



```
$ systemctl --user start schedule-test.service

```

检查你的输出文件（`$HOME/schedule-test-output.txt`），确保你的脚本运行正常。应该只有一个条目，因为我们还没有启动定时器。必要时进行调试。如果你需要更改 .service 单元文件，而不是更改它调用的 shell 脚本，请不要忘记再次启用该服务。


5、一旦作业正常运行，通过为服务启用、启动用户定时器来实时调度作业：



```
$ systemctl --user enable schedule-test.timer
$ systemctl --user start schedule-test.timer

```

请注意，你已经在上面的步骤 4 中启动、启用了服务，因此只需要为它启用、启动定时器。


`enable` 命令会产生如下输出：



```
Created symlink /home/<user>/.config/systemd/user/timers.target.wants/schedule-test.timer → /home/<user>/.config/systemd/user/schedule-test.timer.

```

`start` 命令将只是返回命令行界面提示符。


### 其他操作


你可以检查和监控服务。如果你从系统服务收到错误，下面的第一个命令特别有用：



```
$ systemctl --user status schedule-test
$ systemctl --user list-unit-files

```

手动停止服务：



```
$ systemctl --user stop schedule-test.service

```

永久停止并禁用定时器和服务，重新加载守护程序配置并重置任何失败通知：



```
$ systemctl --user stop schedule-test.timer
$ systemctl --user disable schedule-test.timer
$ systemctl --user stop schedule-test.service
$ systemctl --user disable schedule-test.service
$ systemctl --user daemon-reload
$ systemctl --user reset-failed

```

### 总结


本文以 systemd 定时器为出发点，但是 systemd 的内容远不止于此。这篇文章应该为你提供一个基础。你可以从 [Fedora Magazine systemd 系列](https://fedoramagazine.org/what-is-an-init-system/) 开始探索更多。


### 参考


更多阅读：


* `man systemd.timer`
* `man systemd.service`
* [Use systemd timers instead of cronjobs](https://opensource.com/article/20/7/systemd-timers)
* [Understanding and administering systemd](https://docs.fedoraproject.org/en-US/quick-docs/understanding-and-administering-systemd/)
* <https://opensource.com/> 内有 systemd 速查表




---


via: <https://fedoramagazine.org/systemd-timers-for-scheduling-tasks/>


作者：[Richard England](https://fedoramagazine.org/author/rlengland/) 选题：[lujun9972](https://github.com/lujun9972) 译者：[dcoliversun](https://github.com/dcoliversun) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
Systemd has provided timers for a while and it is worth taking a look at this feature as an alternative to *cron*. This article will show you how to use timers with *systemd* to run a task after the system has booted and on a recurring basis after that. This is not a comprehensive discussion of *systemd*, only an introduction to this one feature.

## Cron vs anacron vs systemd: a quick review

*Cron* can schedule a task to be run at a granularity ranging from minutes to months or more. It is relatively simple to set up, requiring a single configuration file. Although the configuration line is somewhat esoteric. It can also be used by general users.

*Cron*, however, fails if your system happens to not be running when the appropriate execution time occurs.

*Anacron*, overcomes the “system not running” issue. It insures that the task will be executed when your system is again active. While it was intended to be used by administrators, some systems give general users access.

However, the *anacron* frequency of execution can be no less than daily.

Both *cron* and *anacron* have issues with consistency in execution context. Care must be taken that the environment in effect when the task runs is exactly that used when testing. The same shell, environment variables and paths must be provided. This means that testing and debugging can sometimes be difficult.

*Systemd* timers offer the best of both *cron* and *anacron*. Allows scheduling down to minute granularity. Assures that the task will be executed when the system is again running even if it was off during the expected execution time. Is available to all users. You can test and debug the execution in the environment it will run in.

However, the configuration is more involved, requiring at least two configuration files.

If your *cron* and *anacron* configuration is serving you well then there may not be a reason to change. But *systemd* is at least worth investigating since it may simplify any current *cron* /*anacron* work-arounds.

## Configuration

*Systemd* timer executed functions require, at a minimum, two files. These are the “timer unit” and the “service unit”. Actions consisting of more than a simple command, you will also need a “job” file or script to perform the necessary functions.

The timer unit file defines the schedule while the service unit file defines the task(s) performed. More details on the .timer unit is available in “man systemd.timer”. Details on the service unit are available in “man systemd.service”.

There are several locations where unit files exist (listed in the man page). Perhaps the easiest location for the general user, however, is “~/.config/systemd/user”. Note that “user” here, is the literal string “user”.

## Demo

This demo is a simple example creating a user scheduled job rather than a system schedule job (which would run as root). It prints a message, date, and time to a file.

- Start by creating a shell script that will perform the task. Create this in your local “bin” directory, for example, in

“~/bin/schedule-test.sh”

To create the file:touch ~/bin/schedule-test.sh

Then add the following content to the file you just created.

#!/bin/sh echo "This is only a test: $(date)" >> "$HOME/schedule-test-output.txt"

Remember to make your shell script executable.

- Create the .service unit that will call the script above. Create the directory and file in:

“~/.config/systemd/user/schedule-test.service”:

[Unit] Description=A job to test the systemd scheduler [Service] Type=simple ExecStart=/home/<user>/bin/schedule-test.sh [Install] WantedBy=default.target

Note that <user> should be your @HOME address but the “user” in the path name for the unit file is literally the string “user”.

The *ExecStart *line should provide an absolute address with no variables. An exception to this is that for *user* units you may substitute “%h” for $HOME. In other words you can use:

ExecStart=%h/bin/schedule-test.sh

This is only for user unit file use. It is not good for system units since “%h” will always return “/root” when run in the system environment. Other substitutions are found in “man systemd.unit” under the heading “SPECIFIERS”. As it is outside the scope of this article, that’s all we need to know about SPECIFIERS for now.

3. Create a .timer unit file which actually schedules the .service unit you just created. Create it in the same location as the .service file “~/.config/systemd/user/schedule-test.timer”. Note that the file names differ only in their extensions, that is ,”.service” versus “.timer”

[Unit] Description=Schedule a message every 1 minute RefuseManualStart=no # Allow manual starts RefuseManualStop=no # Allow manual stops [Timer] #Execute job if it missed a run due to machine being off Persistent=true #Run 120 seconds after boot for the first time OnBootSec=120 #Run every 1 minute thereafter OnUnitActiveSec=60 #File describing job to execute Unit=schedule-test.service [Install] WantedBy=timers.target

Note that the .timer file has used “OnUnitActiveSec” to specify the schedule. Much more flexible is the “OnCalendar” option. For example:

# run on the minute of every minute every hour of every day OnCalendar=*-*-* *:*:00 # run on the hour of every hour of every day OnCalendar=*-*-* *:00:00 # run every day OnCalendar=*-*-* 00:00:00 # run 11:12:13 of the first or fifth day of any month of the year # 2012, but only if that day is a Thursday or Friday OnCalendar=Thu,Fri 2012-*-1,5 11:12:13

More information on “OnCalendar” is available [here](https://www.freedesktop.org/software/systemd/man/systemd.time.html#Calendar%20Events).

4. All the pieces are in place but you should test to make certain everything works. First, enable the user service:

$ systemctl --user enable schedule-test.service

This should result in output similar to this:

Created symlink /home/<user>/.config/systemd/user/default.target.wants/schedule-test.service → /home/<user>/.config/systemd/user/schedule-test.service.

Now do a test run of the job:

$ systemctl --user start schedule-test.service

Check your output file ( $HOME/schedule-test-output.txt ) to insure that your script is

performing correctly. There should be a single entry since we have not started the timer yet. Debug as necessary. Don’t forget to enable the service again if you needed to change your .service file as opposed to the shell script it invokes.

5. Once the job works correctly, schedule it for real by enabling and starting the user timer for your service:

$ systemctl --user enable schedule-test.timer $ systemctl --user start schedule-test.timer

Note that you have already started and enabled the service in step 4, above, so it is only necessary to enable and start the timer for it.

The “enable” command will result in output similar to this:

Created symlink /home/<user>/.config/systemd/user/timers.target.wants/schedule-test.timer → /home/<user>/.config/systemd/user/schedule-test.timer.

and the “start” will simply return you to a CLI prompt.

## Other operations

You can check and monitor the service. The first command below is particularly useful if you receive an error from the service unit:

$ systemctl --user status schedule-test $ systemctl --user list-unit-files

Manually stop the service:

$ systemctl --user stop schedule-test.service

Permanently stop and disable the timer and the service, reload the daemon config and reset any failure notifications:

$ systemctl --user stop schedule-test.timer $ systemctl --user disable schedule-test.timer $ systemctl --user stop schedule-test.service $ systemctl --user disable schedule-test.service $ systemctl --user daemon-reload $ systemctl --user reset-failed

## Summary

This article will jump-start you with *systemd* timers, however, there is much more to *systemd* than covered here. This article should provide you with a foundation on which to build. You can explore more about it starting in the [Fedora Magazine systemd series ](https://fedoramagazine.org/what-is-an-init-system/).

References – Further reading:

- man systemd.timer
- man systemd.service
[Use systemd timers instead of cronjobs](https://opensource.com/article/20/7/systemd-timers)[Understanding and administering systemd](https://docs.fedoraproject.org/en-US/quick-docs/understanding-and-administering-systemd/)- Also,
[https://opensource.com/](https://opensource.com/)has a good[systemd cheatsheet](https://opensource.com/downloads/linux-systemd-cheat-sheet)

## Ralf

Very nice article, but actually, I would prefer a graphical user interface or management platform for setting up timers, due to the amount of tasks one has to manage and the syntax you need to get used to.

I not dealing very often with the topic.

## Basil

This sounds like a good inclusion for cockpit

## Frank Theile

## Richard England

Indeed, and it has been corrected. Thank you for letting me know.

## Frank Theile

Good article to get rid of

, thanks!

One can also ommit

in the

file and rely on the implicit rule ”

controlls the start of

“, as recommended in the manage.

## Darvond

One thing of note; and something I’ve done for another Fedora install is using these timer services to automate Fedora updates. In fact, I feel there’s an article covering just that.

## Ralf Seidenschwang

There seems to be a option available for displaying timers in Cockpit, but you can’t create a timer from that view under services —> timer. I’ve found a bug from 2017 for that issue.

Ok, I’m unsure if I’m missing a button hidden somewhere else…

## Richard England

If you change your Cockpit session to “Administrative access” then the “timer” category under “Services” will include a “Create timer” button at the top of the page. This does not exist for “Limited access” so I believe the processes will not run as a user, only as root.

I do not have extensive experience with Cockpit so perhaps someone else will be able to elaborate on this.

## Ralf Seidenschwang

I have no root access for Cockpit right now, but will test that soon. Thanks a lot!

## iregognice

You wrote “OnCalender” but it should be “OnCalendar”.

## Richard England

Thank you. Corrections made. Cut’n’paste not necessarily your friend.

## rugk

Note that you can actually also use a CLI command (”systemctl edit –force –full –user schedule-test.service”) to create that service (or timer units etc.) without having to manually create and remember that compliacted file path. 😉

See https://unix.stackexchange.com/q/650484/146739

## Richard England

That’s great to know. Thanks for adding that to the conversation.

## Ralf

I haven’t found the cheat sheet on the first click in the menu, so that would be the direct link: https://opensource.com/downloads/linux-systemd-cheat-sheet

Fantastic website, which I wasn’t aware for whatever reason.

I’ve found a guide for inter-process communication there. I was long searching for an appropriate guide in an suitable length. Perfect!

## Richard England

Thanks, Ralf. I’ve added that more direct link.

## Ralf

Thanks Richard.

## Hugo Leonardo R. D. Lopes

Good evening! I really liked the article. Very well explained. Congratulations. However, there is a caveat that I would like to make and that I have been hitting on this key since 2000. For users who have technical knowledge of Linux it is easy to do, but the community has not yet seen the reality of the world we live in, nor who the people are with no programming or technical knowledge, I would like to use the much talked about Linux. The hotdog guy, the lawyer, the mechanic, the school cook, my grandmother and grandfather, the geography teacher (history, chemistry, physical education, etc…), people who barely know how to send an email or attach something to it. At this point, Windows and Microsoft come out ahead since Windows 95 in terms of the end user’s vision, that is, people without knowledge. As far as the Linux crowd doesn’t make difficult things easy and port everything to an intuitive and easy-to-use graphical interface for anyone. Linux will always play a supporting role in the world of operating systems for simple people. “Wow! Do you use Linux? I wanted to understand how you use it! I prefer Windows, it’s easier!”

## Gregory Bartholomew

The most straight-forward answer is that there are always trade-offs. If Linux were to remove all of those confusing “options” so that there were just a few “easier” things to point and click on, then it would no longer be Linux.

It is very true that not everyone is the same in terms of their computer skills. You might find this 2016 study by the Organisation for Economic Co-operation and Development interesting:The Distribution of Users’ Computer Skills: Worse Than You Think .

A one size fits all design really isn’t possible. Fedora Linux does try to accommodate the variety of users by offering a variety of “spins”. KDE, for example, tries to be more intuitive for people who are familiar with Windows. i3 is for people who do more work on the command line.

## Richard England

Thank you. I’m glad you liked the article.

The article, however, is written for someone that needs or wants to understand scheduling jobs with systemd. That task is something my grandmother, my mother, or the mechanic (don’t sell any of them short) has no need for in daily use on either OS.

Whether Windows is better than Linux really comes down to need and to a very large extent how trained and familiar you are with one or the other. From my experience teaching beginner Linux classes, I feel the opposite as you. I can teach someone who wants to learn how to use the GUI to be very proficient using either OS. There is typically no need for them to delve into the CLI unless they have the desire.

But Linux Desktop vs Windows is an old argument and this is probably not the place to try and solve it.

## Ralf

As a former windows user, I can confirm that the advanced scheduling features are somehow hidden from the user and I would say that most users never view (you will be overwhelmed by the amount of timers windows sets up by default), add or modify timers.

Some developers are working on a GUI here:

https://github.com/cockpit-project/cockpit/issues/15927

I haven’t tested the feature, but I would prefer it for that specific topic.

## mutant

great idea this article. this knowledge is a real life need.

my experience: systemd scheduling is a fat monster that needs to be learned well.

And it has some advantages cron can never catch up with.

So yes, I use both.

Each where apropriate.

Please do never tell one of these mechanismns is always advantageous or better than the other – that would be a stupid lie distracting from there are proper areas of use for each of them.

## Mallikarjungouda S Patil

It’s a very helpful article. Please post more like this on other Linux utilities. Thanks a lot!