三件可以用 systemd 做的令人惊讶的事情
systemd
![](/data/attachment/album/202304/02/135545u0rwtqdemqefme3e.jpg)



> 
> 它不仅仅是为了让你的电脑启动得更快。
> 
> 
> 


当 systemd 刚问世时，有很多关于它能加快启动时间的消息。这项功能对大多数人都有吸引力（对那些不重启的人来说就不那么重要了），所以在很多方面，这也是它今天仍然拥有的声誉。虽然 systemd 确实是在启动过程中并行启动服务起到了作用，但它的作用远不止于此。以下是你可能没有意识到 systemd 可以做的三件事，但你应该好好利用。


### 1、简化 Linux ps


如果你曾经使用过 `ps`，甚至只是 `top` 命令，那么你就会知道你的电脑一直都在运行数百个进程。有时，这正是你需要的信息，以便了解你的计算机或其用户在做什么。其他时候，你真正需要的是一个总体的概览。


`systemd-cgtop` 命令提供了一个基于<ruby> 控制组 <rt>  cgroup </rt></ruby>任务安排的计算机负载的简单视图。[控制组](https://www.redhat.com/sysadmin/cgroups-part-four?intcmp=7013a000002qLH8AAM) 对现代 Linux 很重要，基本上是容器和 Kubernetes 的底层支持结构（这也是云计算可以扩展的原因），但它们也是家庭电脑上的有用结构。例如，从 `systemd-cgtop` 的输出中，你可以看到用户进程的负载，而不是系统进程：



```
Control Group               Proc+   %CPU   Memory  Input/s Output/s
/                             183    5.0     1.6G       0B     3.0M
user.slice                      4    2.8     1.1G       0B   174.7K
user.slice/user-1000.slice      4    2.8   968.2M       0B   174.7K
system.slice                   65    2.2     1.5G       0B     2.8M

```

你也可以只查看你的用户空间进程，或者查看用户空间进程和内核线程。


这绝不是对 `top` 或 `ps` 的替代，而是从一个不同的、独特的角度来观察你的系统。在运行容器时，它可能是至关重要的，因为容器使用控制组。


### 2、Linux 定时任务


[Cron](https://opensource.com/article/17/11/how-use-cron-linux) 是 Linux 的一个经典组件。当你想安排一些事情定期发生时，你会使用 Cron。它很可靠，而且相当好地集成到你的系统中。


问题是，Cron 并不了解有些计算机会被关闭。如果你有一个安排在午夜的 Cron 任务，但你每天在 23:59 关闭你的电脑，那么你的 Cron 任务就永远不会运行。Cron 没有任何工具可以检测到一夜之间错过了工作。


作为对这个问题的回答，有一个很好的 [Anacron](https://opensource.com/article/21/2/linux-automation)，但它不像 Cron 那样集成的好。要让 Anacron 运行，你需要做很多设置。


第二个选择是 systemd 计时器。和 Cron 一样，它也是内置的，可以随时使用。你需要写一个单元文件，这肯定比单行的 Crontab 条目多，但也很简单。例如，这里有一个单元文件，在开机 30 分钟后运行一个假想的备份脚本，但每天只运行一次。这可以确保我的电脑得到备份，并防止它每天尝试备份超过一次。



```
[Unit]
Description=Backup
Requires=myBackup.service

[Timer]
OnBootSec=30min
OnUnitActiveSec=1d

[Install]
WantedBy=timers.target

```

当然，你也可以干预并提示运行一个任务。多亏了 `OnUnitActiveSec` 指令，systemd 不会试图运行你手动激活的作业。


### 3、运行 Linux 容器


容器使启动一个复杂的服务变得非常容易。你可以在短短几分钟内运行一个 [Mattermost](https://opensource.com/education/16/3/mattermost-open-source-chat) 或 Discourse 服务器。在某些情况下，困难的部分是在你运行容器后管理和监控它们。Podman 使得管理它们变得容易，但是用什么来管理 Podman 呢？嗯，[你可以使用 systemd](https://www.redhat.com/sysadmin/podman-run-pods-systemd-services?intcmp=7013a000002qLH8AAM)。


Podman 有一个内置的命令来生成单元文件，这样你的容器就可以被 systemd 管理和监控：



```
$ podman generate systemd --new --files --name example_pod

```

然后你所要做的就是启动服务：



```
$ systemctl --user start pod-example_pod.service

```

和其他服务一样，systemd 确保你的容器荚在任何情况下都能运行。它记录问题，你可以用 `journalctl` 和其他重要的日志来查看，你也可以用 `systemd-cgtop` 在控制组中监控它的活动。


它不是 [Kubernetes 平台](https://www.redhat.com/en/technologies/cloud-computing/openshift/aws?intcmp=7013a000002qLH8AAM)，但对于一两个容器来说，你只需要在可靠和可预测的基础上提供服务，Podman 和 systemd 是一对很棒的组合。


### 下载 systemd 电子书


systemd 的内容还有很多，你可以从作者 [David Both](https://opensource.com/users/dboth) 的新书《[systemd 实用指南](https://opensource.com/downloads/pragmatic-guide-systemd-linux)》中了解基础知识，以及很多实用的技巧。




---


via: <https://opensource.com/article/23/3/3-things-you-didnt-know-systemd-could-do>


作者：[Alan Smithee](https://opensource.com/users/alansmithee) 选题：[lkxed](https://github.com/lkxed/) 译者：[wxy](https://github.com/wxy) 校对：[wxy](https://github.com/wxy)


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


OK
When it first started out, there was a lot of press about systemd and its ability to speed up boot time. That feature had a mostly-universal appeal (it's less important to those who don't reboot), so in many ways, that's the reputation it still has today. And while it's true that systemd is the thing that launches services in parallel during startup, there's a lot more to it than that. Here are three things you may not have realized systemd could do but should be taking advantage. Get more tips from our new downloadable eBook, ** A pragmatic guide to systemd**.

## 1. Simplify Linux ps

If you've ever used the `ps`

or even just the `top`

command, then you know that your computer is running hundreds of processes at any given moment. Sometimes, that's exactly the kind of information you need in order to understand what your computer, or its users, are up to. Other times, all you really need is a general overview.

The `systemd-cgtop`

command provides a simple view of your computer's load based on the cgroups (control groups) tasks have been arranged into. [Control groups](https://www.redhat.com/sysadmin/cgroups-part-four?intcmp=7013a000002qLH8AAM) are important to modern Linux, and are essentially the support structures underneath containers and Kubernetes (which in turn are why the cloud scales the way it does), but also they're useful constructs on your home PC. For instance, from the output of `systemd-cgtop`

, you can see the load of your user processes as opposed to system processes:

```
``````
Control Group Proc+ %CPU Memory Input/s Output/s
/ 183 5.0 1.6G 0B 3.0M
user.slice 4 2.8 1.1G 0B 174.7K
user.slice/user-1000.slice 4 2.8 968.2M 0B 174.7K
system.slice 65 2.2 1.5G 0B 2.8M
```


You can also view just your userspace processes, or just your userspace processes and kernel threads.

This isn't a replacement for `top`

or `ps`

by any means, but it's an additional view into your system from a different and unique angle. And it can be vital when running containers, because containers use cgroups.

## 2. Linux cron

[Cron](https://opensource.com/article/17/11/how-use-cron-linux) is a classic component of Linux. When you want to schedule something to happen on a regular basis, you use cron. It's reliable and pretty well integrated into your system.

The problem is, cron doesn't understand that some computers get shut down. If you have a cronjob scheduled for midnight, but you turn your computer off at 23:59 every day, then your cronjob never runs. There's no facility for cron to detect that there was a missed job overnight.

As an answer to that problem, there's the excellent [anacron](https://opensource.com/article/21/2/linux-automation), but that's not quite as integrated as cron. There's a lot of setup you have to do to get anacron running.

A second alternative is systemd timers. Like cron, it's already built in and ready to go. You have to write a unit file, which is definitely more lines than a one-line crontab entry, but it's also pretty simple. For instance, here's a unit file to run an imaginary backup script 30 minutes after startup, but only once a day. This ensures that my computer gets backed up, and prevents it from trying to backup more than once daily.

```
``````
[Unit]
Description=Backup
Requires=myBackup.service
[Timer]
OnBootSec=30min
OnUnitActiveSec=1d
[Install]
WantedBy=timers.target
```


You can, of course, intervene and prompt a job to run with . Thanks to the `OnUnitActiveSec`

directive, systemd doesn't attempt to run a job you've manually activated.


## 3. Run Linux containers

Containers make starting up a complex service really easy. You can run a [Mattermost](https://opensource.com/education/16/3/mattermost-open-source-chat) or Discourse server in mere minutes. The hard part, in some cases, is managing and monitoring the containers once you have them running. Podman makes it easy to manage them, but what do use to manage Podman? Well, [you can use systemd](https://www.redhat.com/sysadmin/podman-run-pods-systemd-services?intcmp=7013a000002qLH8AAM).

Podman has a built-in command to generate unit files so your containers can be managed and monitored by systemd:

```
````$ podman generate systemd --new --files --name example_pod`


All you have to do then is start the service:

```
````$ systemctl --user start pod-example_pod.service`


As with any other service on your computer, systemd ensures that your pod runs no matter what. It logs problems, which you can view with `journalctl`

along with your other essential logs, and you can monitor its activity within cgroups using `systemd-cgtop`

.

It's no [Kubernetes platform](https://www.redhat.com/en/technologies/cloud-computing/openshift/aws?intcmp=7013a000002qLH8AAM), but for one or two containers that you just want to have available on a reliable and predictable basis, Podman and systemd are an amazing pair.

## Download the systemd eBook

There's a lot more to systemd, and you can learn the basics, along with lots of useful and pragmatic tips, from author [David Both](https://opensource.com/users/dboth) in his new complimentary ** pragmatic guide to systemd**.

## 2 Comments