linux init system and system manager-Systemd learning

1. Overview of Systemd

1.1. Introduction to the init program and its development history

Linux initThe program is the first process started when the system is started. It is responsible for initializing system resources, loading operating system core modules, and starting system services and user processes. The init program is an important part of system startup. It provides a basic environment for subsequent system operations. The init program is usually started by the operating system kernel and is a user-mode process. The init program has a path /sbin/init(a soft connection, linked to the real init process), and its PID is 1. It is the "ancestor" of all processes in the system , all processes in Linux are directly or indirectly created and run by the init process. The init process exists as a daemon process and is responsible for organizing and operating the system's initialization work, allowing the system to enter a defined operating mode. In Linux, there are many ways to implement the init program, such as SysV init, Upstart and Systemd.

The development of the init program can be roughly divided into three stages: sysvinit->upstart->systemd, according to the development characteristics of the init process, it can be simply understood as follows:

SysV init

The earliest Linux distribution used SysV init (System V init), which uses scripts to manage system services. During the startup process, SysV init will start system services in a specific order and run the corresponding startup script. The disadvantage of SysV init is that it starts slowly because it needs to start services one by one in order.

Upstart

Ubuntu has adopted Upstart as the init program since version 8.04. Upstart is an event-driven init program that can start multiple services in parallel to improve system startup speed. Upstart uses configuration files to manage system services. It can automatically monitor the status of services and automatically restart services when they crash or stop running.

Systemd

Systemd is currently the most popular init program, and most Linux distributions use Systemd as the default init program. Through the socket activation mechanism, all programs with or without dependencies are started in parallel, and only the corresponding services are started according to the needs of system startup, maximizing the startup speed. Systemd uses a single configuration file to manage all services and provides rich command line tools to manage services. Systemd also supports dynamic loading and unloading of services, which can be added or removed while the system is running.

1.2. Systemd architecture

Insert image description here

The systemd architecture is as follows:

  • Bottom layer: systemdKernel level dependenciescgroup、autofs、kdbus
  • The second layer: systemd libraries​​is systemd dependent library
  • The third layer: systemd Core​​is systemd’s own library
  • The fourth layer:systemd daemons​​​​ and targets are some basic units and targets that come with it, similar to the scripts that come with sysvinit
  • The top layer is some tools that interact with systemd, such as systemctl;

Insert image description here

1.3. Systemd daemon process

The daemon process of systemd is mainly divided into system state (system) and user state (user)

ps -aux | grep systemd
root          1  0.1  0.0  50144  5864 ?        Ss    2022 361:29 /usr/lib/systemd/systemd --system --deserialize 17
root        618  0.0  0.0  44680  3632 ?        Ss    2022   0:00 /usr/lib/systemd/systemd-udevd
dbus        827  0.1  0.0  58228  4228 ?        Ss    2022 315:04 /usr/bin/dbus-daemon --system --address=systemd: --nofork --nopidfile --systemd-activation
root        884  0.0  0.0  27208  3696 ?        Ss    2022 133:08 /usr/lib/systemd/systemd-logind
root      26750  0.0  0.0 112828  2320 pts/2    S+   16:29   0:00 grep --color=auto systemd
root      34868  0.1  0.0 100940 56832 ?        Ss   Mar18 111:11 /usr/lib/systemd/systemd-journald

The process relationship is as follows:

pstree -p | grep systemd
systemd(1)-+-xxx(17036)-+-{
    
    xxx}(17037)
           |                   |-containerd-shim(88298)-+-systemd(88315)
           |-systemd-journal(34868)
           |-systemd-logind(884)
           `-systemd-udevd(618)

The process with PID 1 /sbin/initis the systemd in the system state, which is a soft link pointing to the real systemd path, which is generally placed in /usr/lib/systemd/the directory in the operating system:

ll /usr/sbin/init
lrwxrwxrwx. 1 root root 22 Mar  4  2022 /usr/sbin/init -> ../lib/systemd/systemd

ll /usr/lib/systemd/systemd
-rwxr-xr-x. 1 root root 1632800 Mar  4  2022 /usr/lib/systemd/systemd

systemd is the general name for a collection of process services. It contains many processes and is responsible for controlling and managing system resources, including the systemd-logincreation, modification and deletion of user login-related information; controlling systemd-sleepsystem hibernation and sleep state switching, etc. Under Ubuntu Kylin operating system, they are mainly concentrated in /usr/lib/systemd/file directories:

ls /usr/lib/systemd/
catalog                 rhel-loadmodules   systemd-cgroups-agent     systemd-localed            systemd-remount-fs      systemd-timedated       system-sleep
import-pubring.gpg      rhel-readonly      systemd-coredump          systemd-logind             systemd-reply-password  systemd-udevd           user
ntp-units.d             system             systemd-cryptsetup        systemd-machined           systemd-rfkill          systemd-update-done     user-generators
rhel-autorelabel        systemd            systemd-fsck              systemd-machine-id-commit  systemd-shutdown        systemd-update-utmp     user-preset
rhel-configure          systemd-ac-power   systemd-hibernate-resume  systemd-modules-load       systemd-shutdownd       systemd-user-sessions
rhel-dmesg              systemd-activate   systemd-hostnamed         systemd-pull               systemd-sleep           systemd-vconsole-setup
rhel-dmraid-activation  systemd-backlight  systemd-importd           systemd-quotacheck         systemd-socket-proxyd   system-generators
rhel-domainname         systemd-binfmt     systemd-initctl           systemd-random-seed        systemd-sysctl          system-preset
rhel-import-state       systemd-bootchart  systemd-journald          systemd-readahead          systemd-sysv-install    system-shutdown

2. Systemd features

Systemd is an init system and system manager for Linux systems. It is one of the most popular init systems currently and is also the default init system for many mainstream Linux distributions (such as Fedora, Red Hat Enterprise Linux, Debian, etc.). Systemd provides many improvements and optimizations in Linux system startup, service management, logging, etc.

2.1. Compatibility

systemd provides features compatible with SysV init. For example, SysV compatibility mode can be used to support SysV init scripts, and the systemd-sysv-generator tool can be used to convert SysV init scripts into Systemd service units to support the SysV process. Existing services and processes in the system do not need to be modified. This reduces the cost of system migration to systemd, making it possible for systemd to replace existing init systems.

2.2. Startup speed

Systemd is a parallel startup init system. Compared with the traditional SysV init, it can start multiple services in parallel, thus improving the system startup speed.
How quickly Systemd starts depends on the number of services started in the system and the order in which they start.

During the startup process, Systemd will start services in parallel based on the dependencies between services , thereby minimizing the waiting time between services and improving startup speed. At the same time, Systemd will also prioritize the services , and start the services with high priority first, so as to speed up the system startup time.

In addition to parallel startup, Systemd also provides some optimizations to improve startup speed. For example, it uses a binary log format to record system logs, which can be parsed and searched faster than the traditional text log format. In addition, Systemd also supports dynamic loading and unloading of services , which can add or remove services while the system is running without restarting the system, thereby reducing system downtime.

In general, Systemd starts relatively quickly and can achieve fast startup on most systems. It also provides some optimization measures to further improve startup speed.

2.3. systemd provides on-demand startup capabilities

When the sysvinit system is initialized, it will start and run all background service processes that may be used. And the system must wait for all services to be started before allowing users to log in. This approach has two disadvantages: first, the startup time is too long, and second, it is a waste of system resources.

It is possible that some services have not been used for a long time, or even for the entire life of the server. For example, CUPS, the printing service is rarely actually used on most servers. You may not have thought that SSHD is rarely actually accessed on many servers. The time spent starting these services is unnecessary; likewise, the system resources spent on these services are a waste.

systemd can provide the ability to start on demand, starting a service only when it is actually requested. When the service ends, systemd can shut it down and start it again the next time it is needed.
This is somewhat similar to inetd in the previous system, and there are many articles on how to migrate services managed by inetd in the past to systemd.

Systemd provides the ability to start services on demand. This feature is often called "Lazy Loading at startup". On-demand startup means that all services or service units are not started immediately when the system starts, but are started when needed. This method can reduce system startup time and resource usage, and avoid unnecessary service startup.

Systemd's on-demand startup function is implemented through the "lazy loading at startup" mechanism. Under this mechanism, Systemd will only start a specific service when it is needed. For example, Systemd automatically starts a service when a user attempts to access it for the first time. In this way, only the services or service units being used in the system can be started, thereby reducing system startup time and resource occupation.

It should be noted that the function of starting services on demand requires the support of the service unit. If a service unit does not support on-demand startup, the service unit will be started immediately whenever the system is started. Therefore, when configuring the Systemd service, special attention needs to be paid to the settings of the on-demand startup mechanism.

2.4. Use Linux cgroups to track and manage the life cycle of the process

systemd utilizes the feature of the Linux kernel, namely cgroups, to complete the tracking task. cgroups is a mechanism provided by the Linux kernel for resource isolation and restriction of processes. Through cgroups, you can limit the use of CPU, memory, disk, network and other resources of the process, and manage and monitor the process. When stopping a service, by querying cgroups, systemd can ensure that all relevant processes are found, thus stopping the service cleanly.
cgroups have been around for a long time and are mainly used to implement system resource quota management. cgroups provides a file system-like interface that is easy to use. When a process creates a child process, the child process inherits the cgroups of the parent process. Therefore, no matter how the service starts a new child process, all these related processes will belong to the same cgroups. Systemd only needs to simply traverse the specified cgroups to correctly find all related processes and stop them one by one.

Systemd uses cgroups to manage and track processes. By creating cgroups, processes are grouped, isolated and restricted. In Systemd, each service unit is assigned to a cgroup, which contains all processes of the service unit, thereby achieving resource isolation and restriction for all processes.

By using cgroups, Systemd can track and manage the life cycle of the process. For example, you can set the CPU usage time, memory limit, IO limit, etc. of the process in cgroups to implement resource limits on the process. In addition, Systemd can also use cgroups to monitor and log processes, thereby providing better system management functions.

2.5. Start the management of mount points and automatic mounting

In traditional Linux systems, users can use /etc/fstabfiles to maintain fixed file system mount points. These mount points are automatically mounted during system startup and are guaranteed to exist once the startup process is complete. These mount points are all file systems that are critical to the operation of the system, such as the HOME directory. Like sysvinit, Systemd manages these mount points so that they can be mounted automatically at system startup. systemd is also compatible with the /etc/fstab file, which you can continue to use to manage mount points.

Systemd uses "mount units" to manage mount points, and each mount unit corresponds to a mount point. The mount unit is a service unit in Systemd. It contains the configuration information of the mount point, including file system type, mount options, device where the mount point is located, mount point path, etc.

In Systemd, you can use systemd-mountcommands to manage mount units, including operations such as creating, modifying, and deleting mount units. Systemd also supports mounting at startup and automatic mounting, which can be achieved in the following ways:

  • “Wants”Mount at startup: Set “Requires”dependencies in the mount unit so that related devices or mount points are automatically mounted when the system starts.

  • Automount: Set in the mount unit “AutoMount”so “yes”that when the relevant device or mount point is accessed, Systemd will automatically mount the device or mount point.

If there is a circular dependency, systemd will not be able to start any service. At this time, systemd will try to solve this problem, because there are two types of dependencies between hives: required is a strong dependency; wanted is a weak dependency. Systemd will remove the dependency specified by the wants keyword to see if it can break the cycle. If it cannot be repaired, systemd will report an error. systemd can automatically detect and fix such configuration errors, greatly reducing the administrator's troubleshooting burden.

It should be noted that when using Systemd for mount point management, you need to pay special attention to the dependencies and mount order of the mount points. For example, if mount point A depends on mount point B, you need to mount B before you can mount A. Therefore, when configuring the mount unit, special attention needs to be paid to the dependencies and mount order of the mount points to ensure that the file system is mounted and used correctly.

Sometimes users also need dynamic mount points. For example, when they plan to access DVD or NFS shared content, the mount is temporarily performed to access the content. When the disc is not accessed, the mount point is canceled (umount) to save resources. . Traditionally, people have relied on the autofs service for this functionality.
Systemd has a built-in automatic mounting service. There is no need to install an additional autofs service. You can directly use the automatic mounting management capabilities provided by systemd to implement the functions of autofs.

2.6. Implement transactional dependency management

The system startup process is composed of many independent tasks, and there may be dependencies among these tasks. For example, mounting an NFS file system must rely on the network to work properly. Although systemd can perform many dependent tasks concurrently to the maximum extent, tasks such as "mounting NFS" and "starting the network" still have inherent sequential dependencies and cannot be executed concurrently. For these tasks, systemd maintains a concept of "transactional consistency" to ensure that all related services can be started normally without interdependence or deadlock.

In Systemd, each service unit can specify a set of dependencies, which can be other service units, sockets, mount points, etc. Systemd uses transactional dependency management to ensure that dependencies are started in the correct order, and to pause or terminate service units when dependencies are not satisfied.

The core idea of ​​transactional dependency management is a transaction, that is, combining all dependencies into a transaction in the correct order, and starting, stopping, or restarting the service unit in the transaction. When a service unit's dependencies are not satisfied, Systemd will pause or terminate the service unit and wait for the dependencies to be satisfied before restarting.

In Systemd, the implementation of transactional dependency management mainly includes the following aspects:

  • Dependency graph analysis: Systemd uses a dependency graph to describe the dependencies between service units, and determines the correct startup sequence by analyzing the dependency graph.

  • Transaction Manager: Systemd uses a transaction manager to manage starting, stopping, or restarting dependencies, and to pause or terminate service units when dependencies are not satisfied.

  • Dependency status tracking: Systemd tracks the status of each dependency and recalculates dependencies when the dependency status changes.

Through transactional dependency management, Systemd can ensure that service units are started in the correct order and that service units are paused or terminated when dependencies are not met, thus improving system stability and reliability.

2.7. Log service

systemd comes with journald, a log service that is responsible for collecting, storing, and managing system logs. It can record all log information when the system is started, including kernel logs, application logs, and service logs. In journald, each log is called a "log entry", which contains log text, timestamp, priority, source and other information. The original intention of the log service is to overcome the shortcomings of the existing syslog service. for example:

syslog is not secure, the content of the message cannot be verified. Every local process can claim to be Apache PID 4711, and syslog believes it and saves it to disk.
The data has no strict format and is very random. Automated log parsers need to analyze human language strings to identify messages. On the one hand, such analysis is difficult and inefficient; on the other hand, changes in the log format will cause the analysis code to be updated or even rewritten.
systemd journal saves all log information in binary format, and users use the journalctl command to view log information. No need to write complex and fragile string analysis handlers yourself.

The advantages of systemd journal are as follows:

简单性:代码少,依赖少,抽象开销最小。
零维护:日志是除错和监控系统的核心功能,因此它自己不能再产生问题。举例说,自动管理磁盘空间,避免由于日志的不断产生而将磁盘空间耗尽。
移植性:日志文件应该在所有类型的 Linux 系统上可用,无论它使用的何种 CPU 或者字节序。
性能:添加和浏览日志非常快。
最小资源占用:日志数据文件需要较小。
统一化:各种不同的日志存储技术应该统一起来,将所有的可记录事件保存在同一个数据存储中。所以日志内容的全局上下文都会被保存并且可供日后查询。例如一条固件记录后通常会跟随一条内核记录,最终还会有一条用户态记录。重要的是当保存到硬盘上时这三者之间的关系不会丢失。syslog 将不同的信息保存到不同的文件中,分析的时候很难确定哪些条目是相关的。
扩展性:日志的适用范围很广,从嵌入式设备到超级计算机集群都可以满足需求。
安全性:日志文件是可以验证的,让无法检测的修改不再可能。

The main functions of Systemd log service include:

  • Automatic rotation: journald can automatically rotate log files to prevent log files from being too large, and can limit the size and number of log files.

  • Message filtering: journald can filter logs based on priority, source, process ID and other conditions, making it easier to view the log information of interest.

  • Log forwarding: journald can forward logs to remote servers or other log collection systems for centralized management and monitoring.

  • Reliability guarantee: journald can ensure the security and reliability of logs through encryption and integrity verification.

When using the Systemd log service, you can use the journalctl tool to view and manage system logs. The journalctl tool provides a wealth of query options, which can query log information based on time, keywords, priorities and other conditions, thereby facilitating problem troubleshooting and fault diagnosis.

In general, the Systemd log service provides powerful system log management functions. It collects, stores and manages system logs through the journald daemon, making it convenient for developers and system administrators to view and analyze system logs, and improving the reliability of the system. and manageability.

3. Systemed unit

Systemd unit is the basic unit for managing and controlling system resources, services or tasks in Systemd. Each unit has a unique name, type and configuration file, and the start and stop sequence of the unit is controlled through dependencies, thereby achieving control. Efficient management and control of system resources and services.

3.1. Common units

Unit is divided into 12 types.

  • Service unit(.service): Used to encapsulate a background service process
  • Target unit(.target): This hive is a logical grouping of other hives. They don't actually do anything themselves, they just reference other hives. This allows for unified control of the configuration unit. This enables the familiar concept of run levels to be implemented. For example, if you want the system to enter the graphical mode, you need to run many services and configuration commands. These operations are represented by configuration units one by one. Combining all these configuration units into a target means that you need to execute all of these configuration units. Once to enter the system running state represented by the target. (For example: multi-user.target is equivalent to runlevel 5 on a legacy system using SysV)
  • Device Unit(.device): This hive encapsulates a device that exists in the Linux device tree. Each device tagged with a udev rule will appear in systemd as a device hive. For devices under the /dev directory
  • Mount Unit(.mount): This type of hive encapsulates a mount point in the hierarchy of the filesystem structure. Systemd will monitor and manage this mount point. For example, it can be automatically mounted at startup; it can be automatically uninstalled under certain conditions. Systemd will convert entries in /etc/fstab into mount points and process them at boot time.
  • Automount Unit(.automount): This type of hive encapsulates a self-mount point in the system structure hierarchy. Each self-mounting hive corresponds to a mounting hive. When the automatic mount point is accessed, systemd performs the mounting behavior defined in the mount point.
  • Path Unit(.path): A file or directory in the file system. Used to monitor changes in specified directories or files and trigger other Units to run
  • Scope Unit(): Used for cgroups, representing processes created from outside systemd. This kind of Unit file is not created by the user, but generated when Systemd is running. It describes the grouping information of some system services.
  • Slice Unit(*.slice): Process group, used in cgroups, represents a group of units arranged hierarchically. The slice does not contain processes, but it forms a hierarchy and places scopes and services in it.
  • Snapshot Unit(.snapshot): It is used to indicate a snapshot of the running status of Systemd Units created by the systemctl snapshot command. Similar to the target configuration unit, the snapshot is a group of configuration units. It saves the current running state of the system.
  • Socket Unit(.socket): This hive encapsulates a socket in the system and the internet. Currently, systemd supports streaming, datagram, and continuous packet AF_INET, AF_INET6, and AF_UNIX sockets. Every socket hive has a corresponding service hive. The corresponding service will be started when the first "connection" enters the socket (for example: nscd.socket starts nscd.service after a new connection)
  • Swap Unit(.swap): Similar to the mount hive, the swap hive is used to manage the swap partition. Users can use the swap configuration unit to define the swap partitions in the system, which can be activated at startup.
  • Timer Unit(.timer): The timer configuration unit is used to regularly trigger user-defined operations. This type of configuration unit replaces traditional timing services such as atd and crontab.
# 列出正在运行的 Unit
$ systemctl list-units
systemctl list-units
  UNIT                                                                  LOAD      ACTIVE SUB       DESCRIPTION
  proc-sys-fs-binfmt_misc.automount                                     loaded    active running   Arbitrary Executable File Formats File System Automount Point
  sys-devices-pci0000:00-0000:00:03.0-virtio0-virtio\x2dports-vport0p1.device loaded    active plugged   /sys/devices/pci0000:00/0000:00:03.0/virtio0/virtio-ports/vpo
  sys-devices-pci0000:00-0000:00:04.0-virtio1-block-vda-vda1.device     loaded    active plugged   /sys/devices/pci0000:00/0000:00:04.0/virtio1/block/vda/vda1
  sys-devices-platform-serial8250-tty-ttyS1.device                      loaded    active plugged   /
......

# 列出所有Unit,包括没有找到配置文件的或者启动失败的
$ systemctl list-units --all

# 列出所有没有运行的 Unit
$ systemctl list-units --all --state=inactive
 UNIT                                                  LOAD      ACTIVE   SUB  DESCRIPTION
  sys-fs-fuse-connections.mount                         loaded    inactive dead FUSE Control File System
  tmp.mount                                             loaded    inactive dead Temporary Directory
  systemd-ask-password-console.path                     loaded    inactive dead Dispatch Password Requests to Console Directory Watch
● display-manager.service                               not-found inactive dead display-manager.service
  ....
# 列出所有加载失败的 Unit
$ systemctl list-units --failed
  UNIT                         LOAD      ACTIVE SUB    DESCRIPTION
● disable_printk_relax.service loaded    failed failed (null)
● httpd.service                loaded    failed failed The Apache HTTP Server
● mariadb.service              loaded    failed failed MariaDB database server
● postfix.service              loaded    failed failed Postfix Mail Transport Agent
● rc-local.service             loaded    failed failed /etc/rc.d/rc.local Compatibility
● walle.service                not-found failed failed walle.service

# 列出所有正在运行的、类型为 service 的 Unit
$ systemctl list-units --type=service

3.2. Systemd directory

  • /etc/systemd/system/: This directory contains configuration files for all local system service unit files, including system services and user services that run at startup.
ls /etc/systemd/system
aegis.service       cpupower.service  default.target.wants  graphical.target.wants  multi-user.target.wants  sysinit.target.wants
basic.target.wants  default.target    getty.target.wants    local-fs.target.wants   sockets.target.wants     system-update.target.wants
  • /usr/lib/systemd/system/: This directory contains service unit files of all installed software, including system services and third-party software services.
ls /usr/lib/systemd/system
arp-ethers.service                      halt.target.wants                  poweroff.target.wants                          systemd-ask-password-console.path
atd.service                             hibernate.target                   printer.target                                 systemd-ask-password-console.service
auditd.service                          htcacheclean.service               proc-sys-fs-binfmt_misc.

...
  • /run/systemd/system/: This directory contains all running service unit files, which are generated based on files in the /etc/systemd/system/ and /usr/lib/systemd/system/ directories.
ls /run/systemd/system
session-215677.scope    session-401915.scope.d  session-402358.scope    session-c4042067.scope.d  session-c6917125.scope    user-0.slice.d
session-215677.scope.d  session-401918.scope    session-402358.scope.d  session-c5481555.scope    session-c6917125.scope.d  user-1367771.slice
session-285125.scope    session-401918.scope.d  session-c16.scope       session-c5481555.scope.d  session-c92156.scope      user-1367771.slice.d
session-285125.scope.d  session-401919.scope    session-c16.scope.d     session-c56.scope         session-c92156.scope.d
session-401915.scope    session-401919.scope.d  session-c4042067.scope  session-c56.scope.d       user-0.slice
  • /etc/systemd/system.conf: This file contains the global configuration of Systemd.

  • /etc/systemd/user/: This directory contains user-defined service unit files, which will be automatically started when the user logs in.

  • /etc/systemd/logind.conf: This file contains the configuration of the login manager, which is used to manage the session when the user logs in.

  • /etc/systemd/systemd-journald.conf`: This file contains the configuration of the journal log, which is used to manage the system log.

  • /etc/systemd/timesyncd.conf: This file contains the configuration of the timesyncd time synchronization service.

  • /usr/lib/systemd/systemd-sleep: This directory contains service scripts related to sleep mode.

3.3. Unit and Target

Unit: Unit is the basic building block of Systemd, used to define system services and other resources, including service startup sequence, dependencies, deployment status, etc. Each Unit has a unique name and type, such as service, socket, mount, etc.

In the Unit file, the following information can be defined:

Unit 的类型、名称和描述
Unit 之间的依赖关系和启动顺序
Unit 的执行程序、启动参数和环境变量
Unit 的状态和执行结果
Unit 的启动、停止、重启和状态查询等操作

Target: Target is a collection of related Units, used to define the target state of system operation. Each Target has a unique name and a set of dependent Units. When the system starts, Systemd will try to start the specified Target to meet the needs of system operation.

In the Target file, you can define the following information:

Target 的名称和描述
Target 所包含的 Unit 和依赖关系
Target 的启动、停止、重启和状态查询等操作

The type of Target is similar to the type of Unit, such as multi-user, graphical, network, etc. Among them, multi-user.target is used to start the multi-user command line interface, graphical.target is used to start the graphical interface, network.target is used to start network services, etc.

In short, Unit and Target are the core concepts of Systemd. By defining Unit and Target, system services and status can be managed and controlled.

# 查看target类型的unit
$ systemctl list-unit-files --type=target

# 查看指定target下面有哪些unit
$ systemctl list-dependencies multi-user.target

# 查看系统默认的target
$ systemctl get-default
multi-user.target

sudo systemctl set-default multi-user.target
# 切换 Target 时,默认不关闭前一个 Target 启动的进程,systemctl isolate 命令改变这种行为,关闭前一个 Target 里面所有不属于后一个 Target 的进程
sudo systemctl isolate multi-user.target
# 查看配置文件
systemctl cat multi-user.target

# 修改配置文件以后,需要重新加载配置文件,然后重新启动相关服务
# 重新加载配置文件
sudo systemctl daemon-reload
# 重启相关服务
sudo systemctl restart foobar

cat /usr/lib/systemd/system/sshd.service//Check which target a service belongs to. You only need to look at [install]the part to see which target it belongs to.

$ cat /usr/lib/systemd/system/sshd.service
[Unit]
Description=OpenSSH server daemon
Documentation=man:sshd(8) man:sshd_config(5)
After=network.target sshd-keygen.service
Wants=sshd-keygen.service

[Service]
Type=notify
EnvironmentFile=/etc/sysconfig/sshd
ExecStart=/usr/sbin/sshd -D $OPTIONS
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure
RestartSec=42s

[Install]
WantedBy=multi-user.target

The main differences between Target and SysV-init processes:

  • The default RunLevel (set in the /etc/inittab file) is now replaced by the default Target, usually a /etc/systemd/system/default.targetsymbolic link to graphical.target (graphical interface) or multi-user.target (multi-user command line)

  • The location of the startup script, which used to be /etc/init.dthe directory, is symbolically linked to different RunLevel directories (such as /etc/rc3.d, /etc/rc5.d, etc.), and is now stored in /lib/systemd/system 和 /etc/systemd/systemthe directory

  • The location of the configuration file. In the past, the configuration file of the init process was /etc/inittab, and the configuration files of various services were stored in /etc/sysconfigthe directory. The current configuration files are mainly stored in /lib/systemdthe directory. /etc/systemdModifications in the directory can overwrite the original settings.

3.4. Unit status

In Systemd, the status of Unit has the following types:

  • active (running): Unit is running.
  • active (exited): Unit has finished running and exited.
  • inactive (dead): Unit has stopped running.
  • activating (start): Unit is starting.
  • activating (auto-restart): Unit is restarting automatically.
  • deactivating (stop): Unit is stopping.
  • deactivating (restart): Unit is restarting.
  • failed: Unit failed to start, or stopped suddenly during operation.

Common commands

# 显示系统状态
$ systemctl status

# 显示单个 Unit 的状态
$ sysystemctl status bluetooth.service

# 显示远程主机的某个 Unit 的状态
$ systemctl -H [email protected] status httpd.service

# 显示某个 Unit 是否正在运行
$ systemctl is-active application.service

# 显示某个 Unit 是否处于启动失败状态
$ systemctl is-failed application.service

# 显示某个 Unit 服务是否建立了启动链接
$ systemctl is-enabled application.service

3.5. Common unit management commands

# 立即启动一个服务
$ sudo systemctl start apache.service

# 立即停止一个服务
$ sudo systemctl stop apache.service

# 重启一个服务
$ sudo systemctl restart apache.service

# 杀死一个服务的所有子进程
$ sudo systemctl kill apache.service

# 重新加载一个服务的配置文件
$ sudo systemctl reload apache.service

# 重载所有修改过的配置文件
$ sudo systemctl daemon-reload

# 显示某个 Unit 的所有底层参数
$ systemctl show httpd.service

# 显示某个 Unit 的指定属性的值
$ systemctl show -p CPUShares httpd.service

# 设置某个 Unit 的指定属性
$ sudo systemctl set-property httpd.service CPUShares=500

3.6. Unit dependencies

In Systemd, dependencies can be established between Units to ensure that they start and stop in the correct order. The following are several types of dependencies between Units:

  • Requires: Indicates that Unit A depends on Unit B. If Unit B cannot start, Unit A cannot start either.

  • Wants: Indicates that Unit A wants to depend on Unit B, but if Unit B fails to start, Unit A can still start.

  • RequiresOverridable: Similar to Requires, but allows dependent Units to be overridden at startup, such as when running in a container.

  • BindsTo: Indicates that Unit A depends on Unit B. If Unit B stops running, Unit A will also be stopped.

  • PartOf: Indicates that Unit A is part of Unit B. If Unit B stops running, Unit A will also be stopped.

  • Conflicts: Indicates that Unit A conflicts with Unit B. If Unit B is running, Unit A cannot start.

In a Unit file, dependencies can be defined using the following syntax:

[Unit]
Requires=unit1.service
Wants=unit2.service
BindsTo=unit3.socket
PartOf=unit4.target
Conflicts=unit5.service

Among them, unit1.service, unit2.service, etc. are all names of Unit. By establishing correct dependencies, you can ensure that system services start and stop in the correct order, thus avoiding problems caused by incorrect dependencies.
Common commands:

# 列出一个 Unit 的所有依赖
$ systemctl list-dependencies nginx.Service

# 上述命令默认不会显示target 类型依赖,需要展示,使用如下命令
$ systemctl list-dependencies --all nginx.service

3.7, unit file

Take /usr/lib/systemd/system/docker.serviceas an example, let’s learn how to write unit files:

[Unit]
Description=Docker Application Container Engine
Documentation=https://docs.docker.com
BindsTo=containerd.service
After=network-online.target firewalld.service containerd.service
Wants=network-online.target
Requires=docker.socket

[Service]
Type=notify
# the default is not to use systemd for cgroups because the delegate issues still
# exists and systemd currently does not support the cgroup feature set required
# for containers run by docker
ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock
ExecReload=/bin/kill -s HUP $MAINPID
TimeoutSec=0
RestartSec=2
Restart=always

# Note that StartLimit* options were moved from "Service" to "Unit" in systemd 229.
# Both the old, and new location are accepted by systemd 229 and up, so using the old location
# to make them work for either version of systemd.
StartLimitBurst=3

# Note that StartLimitInterval was renamed to StartLimitIntervalSec in systemd 230.
# Both the old, and new name are accepted by systemd 230 and up, so using the old name to make
# this option work for either version of systemd.
StartLimitInterval=60s

# Having non-zero Limit*s causes performance problems due to accounting overhead
# in the kernel. We recommend using cgroups to do container-local accounting.
LimitNOFILE=infinity
LimitNPROC=infinity
LimitCORE=infinity

# Comment TasksMax if your systemd version does not supports it.
# Only systemd 226 and above support this option.
TasksMax=infinity

# set delegate yes so that systemd does not reset the cgroups of docker containers
Delegate=yes

# kill only the docker process, not all processes in the cgroup
KillMode=process

[Install]
WantedBy=multi-user.target
  • Unit section: This section is common to all Unit files and is used to define the Unit's metadata, configuration and relationship with other Units. Description describes the Unit file information, Documentation represents the document of the specified service, and Condition represents the conditions for service startup. Some Units also include wants, before, after, require fields, these represent a dependency of the service.
  • Install segment: This part is common to all Unit files, and usually specifies the target of the running target, so that the service runs automatically when the system starts. Wantedby and RequiredBy are similar to the Wants field in the Unit section, indicating dependencies, and the Alias ​​field indicates the alias used when starting the runtime.
  • service segment: a unique field of the Unit file of the Service type, used to define the specific management and execution actions of the service. It includes the Type field, which defines the behavior of the process, such as starting using fork(), starting using dbus, etc.; ExecStart, ExecStartPre, ExecStartPos, ExecReload, and ExecStop respectively represent the command executed before starting the current service, the command executed before starting the current service, and the startup The command to start after the current service, the command to execute when the current service is restarted, and the command to execute when the current service is stopped.

3.7.1. Unit segment parameters

  • Description: Information describing this Unit file

  • Documentation: Specifies the document of the service, which can be the URL path of one or more documents

  • Requires: A list of other Units that depend on, and the Unit templates listed in it will be started when the service is started. And, if any of the services fails to start, the service will also be terminated

  • Wants: Similar to Requires, but only triggers the startup of each Unit module listed when the configured Unit starts, regardless of whether the startup of these templates is successful.

  • After: Similar to Requires, but the current service will not be started until all the modules listed later are started

  • Before: Contrary to After, between starting a specified task and a module, it will first confirm that the current service has been running

  • Binds To: Similar to Requires, it fails when it fails and succeeds when it succeeds. However, if any of these templates ends or restarts unexpectedly, the service will also be terminated or restarted.

  • Part Of: A subset of the Bind To function. It will only terminate or restart the current service when the listed task module fails or restarts, and will not start with the startup of the listed template.

  • OnFailure: When this template fails to start, each module listed will be automatically started

  • Conflicts: A module that conflicts with this module. If any of the listed modules is already running, the service cannot be started, and vice versa

3.7.2. Install section parameters

The target module of this part of the configuration is usually a .target file for a specific running target, which is used to make the service run automatically when the system starts. This section can contain three launch constraints:

  • WantedBy: Similar to Wants in the Unit section, only the modules listed later are not the modules that the service depends on, but the modules that depend on the current service. Its value is one or more Targets. When the current Unit is activated (enable), the symbolic link will be placed in the subdirectory formed /etc/systemd/systemby <Target 名> + .wantsthe suffix under the directory, such as/etc/systemd/system/multi-user.target.wants/

  • RequiredBy: Similar to Wants in the Unit section, only the modules listed later are not the modules that the service depends on, but the modules that depend on the current service. Its value is one or more Targets. When the current Unit is activated, the symbolic link will be placed in the subdirectory formed /etc/systemd/systemby the suffix under the directory<Target 名> + .required

  • Also: When the current Unit is enabled/disabled, other Units are enabled/disabled at the same time.

  • Alias: Aliases that the current Unit can be used to start

3.7.3. Service segment parameters

It is used for Service configuration, only the Unit of Service type has this block. Its main fields are divided into two aspects: service life cycle and service context configuration

Service life cycle control related
  • Type: Defines the behavior of the process at startup, it has the following values:

    • Type=simple: Default value, execute the command specified by ExecStart to start the main process

    • Type=forking: Create a child process from the parent process by fork, and the parent process will exit immediately after creation

    • Type=oneshot: One-time process, Systemd will wait for the current service to exit before continuing to execute

    • Type=dbus: The current service is started via D-Bus

    • Type=notify: After the current service is started, Systemd will be notified, and then continue to execute

    • Type=idle: The current service will only run if other tasks have been completed.

  • RemainAfterExit: Value is true or false (default). When configured to true, Systemd will only be responsible for starting the service process. Even if the service process exits, Systemd will still think that the service is still running. This configuration is mainly provided for some special types of services that are not memory-resident, but exit immediately after starting the registration, and then wait for messages to start on demand.

  • ExecStart: command to start the current service

  • ExecStartPre: The command executed before starting the current service

  • ExecStartPost: Command executed after starting the current service

  • ExecReload: Command executed when restarting the current service

  • ExecStop: The command executed when the current service is stopped

  • ExecStopPost: Stop the command executed after its service

  • RestartSec: The number of seconds between automatic restarts of the current service

  • Restart: Define under what circumstances Systemd will automatically restart the current service. Possible values ​​include always (always restart), on-success, on-failure, on-abnormal, on-abort, on-watchdog

  • TimeoutStartSec: The number of seconds to wait when starting the service. This configuration is particularly important for using Docker containers, because the image may need to be downloaded when running for the first time. Severe delays may easily cause Systemd to misjudge it as a startup failure and kill it. Typically, for this kind of service, specify this value as 0, thus turning off timeout detection

  • TimeoutStopSec: The number of seconds to wait when stopping the service. If it is still not stopped after this time, Systemd will use the SIGKILL signal to forcibly kill the service process.

  • KillMode: Defines how Systemd stops the sshd service.

    • control-group(Default value): All child processes in the current control group will be killed.

    • process: Kill only the main process

    • mixed: The main process will receive the SIGTERM signal, and the child process will receive the SIGKILL signal.

    • none: No process will be killed, only the stop command of the service will be executed.

Service context configuration related
  • Environment: Specify environment variables for the service

  • EnvironmentFile: Specifies to load a file containing a list of environment variables required by the service. Each line in the file is the definition of an environment variable. The key=value key-value pair inside the file can be in the form of $key, in the current configuration get from file

  • Nice: The process priority of the service. The smaller the value, the higher the priority. The default is 0. Among them, -20 is the highest priority and 19 is the lowest priority.

  • WorkingDirectory: specifies the working directory of the service

  • RootDirectory: Specify the root directory of the service process (/ directory). If this parameter is configured, the service will not be able to access any files outside the specified directory.

  • User:Specify the user running the service

  • Group:Specify the user group to run the service

  • MountFlags: The Mount Namespace configuration of the service will affect the mount point information in the process context, that is, whether the service will inherit the existing mount point on the host, and if the service runs and performs the operation of mounting or unmounting the device, whether it will actually be installed on the host. effects on the host. Optional values ​​are shared, slaved or private

    • shared: The service and the host share a Mount Namespace, inherit the host mount point, and the device mounted or uninstalled by the service will be truly reflected on the host.

    • slave: The service uses an independent Mount Namespace, which will inherit the host's mount point, but the service's operations on the mount point only take effect within its own Namespace and will not be reflected on the host.

    • private: The service uses an independent Mount Namespace. It does not have any mount points when it is started, and the service's operations on the mount points will not be reflected on the host.

  • LimitCPU / LimitSTACK / LimitNOFILE / LimitNPROCEtc.: Limit the amount of system resources for a specific service, such as CPU, program stack, number of file handles, number of child processes, etc.

  • Log related classes, here output to journal, otherwise the default is syslog

StandardError=journal

StandardOutput=journal

StandardInput=null

Note: If Linux commands are used in the ExecStart, ExecStop and other properties, the complete absolute path must be written. For the ExecStartPre and ExecStartPost auxiliary commands, if there is a "-" symbol in front, it means that errors in these commands are ignored. Because some "auxiliary" commands may not necessarily succeed, such as trying to clear a file, but the file may not exist.

3.7.4. Unit file placeholder

In the Unit file, sometimes you need to use some information related to the running environment, such as the node ID, the user who runs the service, and so on. These information can be represented by placeholders, and then the actual values ​​are dynamically replaced during actual operation.

  • %n: Complete Unit file name, including .service suffix

  • %p: The part before the @ symbol in the Unit template file name, excluding the @ symbol

  • %i: The part after the @ symbol in the Unit template file name, excluding the @ symbol and the .service suffix

  • %t: The directory where the system running files are stored, usually "run"

  • %u: The user running the service, if not specified in the Unit file, it defaults to root

  • %U:User ID running the service

  • %h: The Home directory of the user running the service, that is, the value of the %{HOME} environment variable

  • %s: The default shell type of the user running the service, which is the value of the %{SHELL} environment variable

  • %m: The Machine ID of the actual running node, which is useful for each service in the running location

  • %b: Boot ID, which is a random number that is different for each node and will change every time the node restarts

  • %H: The host name of the actual running node

  • %v: The kernel version, which is the output of the "uname -r" command

  • %%: Represents an ordinary percent sign in the Unit template file

3.7.5. Unit template

In Systemd, Unit template is a special Unit file used to define multiple similar Units. The template file itself does not start any services, but is used to generate the actual Unit file. This mechanism allows users to generate multiple similar Unit files through templates, thereby simplifying the configuration process.

The file name of the Unit template starts with the @ symbol, for example, [email protected]. In the template file, you can use the %i placeholder to represent the actual instance name. When Systemd starts a specific Unit instance, %i will be replaced with the instance name.

The following is a simple Unit template example:

[Unit]
Description=My Service Template

[Service]
ExecStart=/usr/bin/myservice --name=%i

[Install]
WantedBy=multi-user.target

In this example, the template file defines a template named [email protected] and contains an ExecStart directive, where %i is used to represent the instance name. This template can be used to generate multiple actual Unit files, eg [email protected][email protected].

Using Systemd's template mechanism can easily generate multiple similar Unit files, thereby simplifying the configuration process and improving efficiency.

3.8. Service life cycle

When a new Unit file is placed in the /etc/systemd/system/ or /usr/lib/systemd/system/ directory, it will not be recognized by itself.
In Systemd, the life cycle of a service includes the following stages:

  • Loading phase: Systemd loads the Unit file of the service and starts or disables the service according to the configuration.

  • Preparation phase: Systemd prepares the startup environment of the service, including setting environment variables, creating required directories, checking dependencies, and so on.

  • Startup phase: Systemd starts the service, executes the startup command or program of the service, and records the PID of the service.

  • Running phase: During the normal operation of the service, Systemd monitors the status of the service, records logs, processes signals, and other operations.

  • Stop phase: When the service needs to be stopped, Systemd sends a stop signal to the service process and waits for the service process to exit.

  • Post-stop processing phase: When the service process exits, Systemd executes the post-stop processing command or program of the service and records the exit status of the service.

  • Uninstall phase: When the service is no longer needed, Systemd unloads the service's Unit file and cleans up related runtime files and logs.

In addition to the above stages, Systemd also provides other functions, such as automatic restart, service status query, dependency management, etc. Through the management of Systemd, the running status of system services can be managed and monitored more conveniently.

3.8.1. Activation of services

  • systemctl enable: Establish a symbolic link to the service in /etc/systemd/system/, pointing to /usr/lib/systemd/system/

  • systemctl start: Start the ExecStartPre, **ExecStart ** and **ExecStartPost ** commands defined in the Unit file in sequence

3.8.2. Service start and stop

  • systemctl start: Start the ExecStartPre, ExecStart and ExecStartPost commands defined in the Unit file in sequence

  • systemctl stop: Stop the ExecStopPre, ExecStop and ExecStopPost commands defined in the Unit file in sequence

  • systemctl restart:Restart service

  • systemctl kill: Kill the service immediately

3.8.3. Startup and cancellation of services

  • systemctl enable: In addition to activating the service, you can also set the service to start at boot.

  • systemctl disable: Cancel the booting of the service

3.8.4. Modification and removal of services

  • systemctl daemon-reload: Systemd will write the contents of the Unit file to the cache, so when the Unit file is updated, Systemd needs to be told to re-read all Unit files.

  • systemctl reset-failed: Remove Unit files marked as missing. After deleting the Unit file, due to the relationship of the cache, even if the cache is updated through daemon-reload, the Unit marked as not-found will still be displayed in the list-units.

3.9. Log management

In Systemd, all system services will generate log records, including service start, stop, error messages, etc. Systemd uses the Journal logging system to manage and store these logs. The Journal logging system provides the following advantages:

  • Support multiple log formats: Journal log system supports multiple log formats, including text format, binary format, JSON format, etc.

  • Support efficient log compression: Journal log system can automatically compress logs and support fast query of compressed logs.

  • Support efficient log filtering: Journal log system supports efficient log filtering, and can query logs based on service name, event type, time range and other conditions.

  • Support efficient log rotation: Journal log system supports efficient log rotation, which can automatically delete expired logs and limit the size of log files within a certain range.

In Systemd, you can use the following commands to query and manage logs:

  • journalctl: This command can query system logs, including service start, stop, error information, etc. Logs can be queried based on service name, event type, time range and other conditions.

  • journalctl --follow: This command can track log changes in real time, similar to the tail -f command.

  • journalctl --vacuum-size=100M: This command can limit the log file size. When the file size exceeds the specified value, expired logs will be automatically deleted.

  • journalctl --vacuum-time=1week: This command can limit the storage time of log files. When the storage time of log files exceeds the specified time, expired logs will be automatically deleted.

In short, through Systemd's Journal logging system, you can easily manage and query system logs and speed up troubleshooting.

Other common commands:

# 查看所有日志(默认情况下 ,只保存本次启动的日志)
sudo journalctl

# 查看内核日志(不显示应用日志):--dmesg 或 -k
sudo journalctl -k

# 查看系统本次启动的日志(其中包括了内核日志和各类系统服务的控制台输出):--system 或 -b
sudo journalctl -b
sudo journalctl -b -0

# 查看上一次启动的日志(需更改设置)
sudo journalctl -b -1

# 查看指定服务的日志:--unit 或 -u
sudo journalctl -u docker.servcie

# 查看指定服务的日志
sudo journalctl /usr/lib/systemd/systemd

# 实时滚动显示最新日志
sudo journalctl -f

# 查看指定时间的日志
sudo journalctl --since="2021-10-30 18:17:16"
sudo journalctl --since "20 min ago"
sudo journalctl --since yesterday
sudo journalctl --since "2022-01-10" --until "2022-01-11 03:00"
sudo journalctl --since 09:00 --until "1 hour ago"

# 显示尾部的最新 10 行日志:--lines 或 -n
sudo journalctl -n

# 显示尾部指定行数的日志
sudo journalctl -n 20

# 将最新的日志显示在前面
sudo journalctl -r -u docker.service

# 改变输出的格式:--output 或 -o
sudo journalctl -r -u docker.service -o json-pretty

# 查看指定进程的日志
sudo journalctl _PID=1

# 查看某个路径的脚本的日志
sudo journalctl /usr/bin/bash

# 查看指定用户的日志
sudo journalctl _UID=33 --since today

# 查看某个 Unit 的日志
sudo journalctl -u nginx.service
sudo journalctl -u nginx.service --since today

# 实时滚动显示某个 Unit 的最新日志
sudo journalctl -u nginx.service -f

# 合并显示多个 Unit 的日志
journalctl -u nginx.service -u php-fpm.service --since today

# 查看指定优先级(及其以上级别)的日志,共有 8 级
# 0: emerg
# 1: alert
# 2: crit
# 3: err
# 4: warning
# 5: notice
# 6: info
# 7: debug
sudo journalctl -p err -b

# 日志默认分页输出,--no-pager 改为正常的标准输出
sudo journalctl --no-pager

# 以 JSON 格式(单行)输出
sudo journalctl -b -u nginx.service -o json

# 以 JSON 格式(多行)输出,可读性更好
sudo journalctl -b -u nginx.service -o json-pretty

# 显示日志占据的硬盘空间
sudo journalctl --disk-usage

# 指定日志文件占据的最大空间
sudo journalctl --vacuum-size=1G

# 指定日志文件保存多久
sudo journalctl --vacuum-time=1years

4. systemd.timer scheduled tasks

In Systemd, in addition to services (Units), timers can also be used to manage and control scheduled tasks. Compared with traditional crontab, using Systemd's timer can provide higher flexibility and reliability.

Timer is essentially a Unit, which can define the execution time and execution commands of scheduled tasks. Timer can be set to start once, daily, weekly, monthly and other different time intervals.

4.1. Advantages of systemd.timer

  • Automatically generate logs and cooperate with Systemd's log tool, which is very convenient for debugging

  • You can set the usage quota of memory and CPU, for example, use up to 50% of CPU

  • Tasks can be split and depend on other Systemd units to complete very complex tasks

4.2. Detailed explanation of examples

Create a test.timer (generally recommend the same name) file in /usr/lib/systemd/system

[Unit]
Description=My test Timer

[Timer]
OnBootSec=2m
OnUnitActiveSec=10s
OnCalendar=*-*-* 00:00:00
Unit=myjob.service

[Install]
WantedBy=timers.target
定时器单元文件中必须包含一个 [Timer]

通过同时使用 OnBootSec=OnUnitActiveSec= 指令, 就可以实现在系统启动后的某个时间点启动匹配单元, 并且之后每隔一段时间周期性的反复启动匹配单元

时间单位后缀:us(微秒), ms(毫秒), s(), m(), h(), d(), w()。 如果省略了时间单位,那么表示使用默认单位"秒"

Unit= 该定时器单元的匹配单元, 也就是要被该定时器启动的单元。默认值是与此定时器单元同名的服务单元

When the Timer starts, Systemd will calculate the next execution time based on the OnCalendar parameter, and start the corresponding service or command when the time arrives. Timer's execution log will be recorded in Systemd's Journal log, which can be viewed using the journalctl command.

Before starting the Timer, you need to use the systemctl enable command to add the Timer to the self-starting list.

systemctl enable mytimer.timer

Commonly used commands:

# 启动刚刚新建的这个定时器
sudo systemctl start test.timer

# 查看这个定时器的状态
systemctl status test.timer

# 查看所有正在运行的定时器
systemctl list-timers

# 关闭这个定时器
sudo systemctl stop myscript.timer

# 下次开机,自动运行这个定时器
sudo systemctl enable myscript.timer

# 关闭定时器的开机自启动
sudo systemctl disable myscript.timer

# 查看整个日志
sudo journalctl

# 查看 test.timer 的日志
sudo journalctl -u test.timer

# 查看 test.timer 和 test.service 的日志
sudo journalctl -u test

# 从结尾开始查看最新日志
sudo journalctl -f

# 从结尾开始查看 test.timer 的日志
journalctl -f -u test.timer

4.3. Detailed explanation of Timer parameters

4.3.1. The Timer unit file is divided into several parts

[Unit]Partially defined metadata.

[Timer]Partially customizable timer. Systemd provides some of the following fields

  • OnActiveSec: After the timer takes effect, how long does it take to start executing the task?

  • OnBootSec: After the system starts, how long does it take to start executing the task?

  • OnStartupSec: After the Systemd process is started, how long does it take to start executing the task?

  • OnUnitActiveSec: How long to wait for the unit to be executed again after it was last executed.

  • OnUnitInactiveSec: How much time has elapsed since the timer was last closed before it is executed again

  • OnCalendar: Execution based on absolute time, not relative time

  • AccuracySec: If the task must be postponed for various reasons, the maximum number of seconds to postpone is 60 seconds by default.

  • Unit: The actual task to be executed, the default is the unit with the same name and the .service suffix.

  • Persistent: If this field is set, even if the timer does not start when the timer expires, the corresponding unit will be automatically executed.

  • WakeSystem: If the system sleeps, whether to automatically wake up the system

In the example script, OnUnitActiveSec=1hit means that the task will be executed once an hour. Other ways of writing include OnUnitActiveSec=*-*-* 02:00:00executing it at 2 a.m. every day, and OnUnitActiveSec=Mon *-*-* 02:00:00executing it at 2 a.m. every Monday. Please refer to the official documentation for details.

4.3.2, [Install] and target

  • test.timerIn the file, there is also an [Install] section, which defines the commands to be executed when the unit is automatically started at boot (systemctl enable) and turned off (systemctl disable). In the above script, only one field is written in the [Install] part, that is WantedBy=multi-user.target. What it means is that if it is executed systemctl enable test.timer(the timer will automatically take effect as long as the computer is turned on), then the timer belongs to multi-user.target.

  • The so-called Target refers to a group of related processes, a bit like the startup level under the init process mode. When a Target is started, all processes belonging to this Target will be started. multi-user.target is the most commonly used Target, which means multi-user mode. That is, when the system starts in multi-user mode, test.timer will be started together. The operation behind it is actually very simple. systemctl enable test.timerWhen the command is executed, multi-user.target.wantsa symbolic link will be created in the directory pointing to test.timer

Reference documentation:

1、https://blog.51cto.com/weiyigeek/5666902

2、https://blog.csdn.net/lemon_TT/article/details/127090001

3、https://blog.csdn.net/qq_35995514/article/details/125582824

4、https://www.cnblogs.com/aaronLinux/p/6861425.html

Guess you like

Origin blog.csdn.net/yuelai_217/article/details/130949299