How to configure a systemd service unit to execute a command or script at system shutdown
https://access.redhat.com/solutions/2608901
SOLUTION 已验证 - 已更新 2016年九月20日14:07 -
环境
- Red Hat Enterprise Linux 7
问题
-
How can I create a systemd service unit in RHEL 7 that executes something only at shutdown/reboot time?
-
How to run a service script right before shutdown in RHEL 7?
决议
There are two common ways to approach this. The author prefers the former.
(1) Service unit that ONLY executes task immediately prior to entering shutdown.target
-
With this approach, the service unit cannot be manually started or stopped; it will only be triggered on system shutdown/reboot
-
Customize the maroon-colored text in the following example:
~]# cat /etc/systemd/system/mycustom.service [Unit] Description=Run my custom task at shutdown DefaultDependencies=no Before=shutdown.target RefuseManualStart=true [Service] Type=oneshot ExecStart=/bin/touch /root/somefile [Install] WantedBy=shutdown.target ~]# systemctl daemon-reload ~]# systemctl enable mycustom ~]# reboot
(2) Service unit that executes a task whenever unit is stopped, including at system shutdown
-
With this approach, the service unit can be stopped at will via
systemctl stop, which could be a benefit or a detriment, depending on requirements -
Customize the maroon-colored text in the following example:
~]# cat /etc/systemd/system/mycustom.service [Unit] Description=Run my custom task at service stop [Service] Type=oneshot RemainAfterExit=true ExecStop=/bin/touch /root/somefile [Install] WantedBy=multi-user.target ~]# systemctl daemon-reload ~]# systemctl enable mycustom --now ~]# reboot
Notes
-
Note that as with all systemd units, both approaches are subject to systemd's timeout settings, namely:
DefaultTimeoutStartSec=andDefaultTimeoutStopSec=from/etc/systemd/system.conf -
To allow the commands to take more than 90sec, add
TimeoutSec=3minorTimeoutSec=0(disabled) to the[Service]section of the unit file -
See
man systemd.servicefor more detail onTimeout*directives
本文介绍在RHEL7中创建systemd服务单元的方法,该服务单元可在系统关机或重启时执行特定命令或脚本。提供了两种实现方式:一种仅在进入关机目标时执行任务,另一种在服务单元停止时执行任务,包括系统关机。
869

被折叠的 条评论
为什么被折叠?



