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=3min
orTimeoutSec=0
(disabled) to the[Service]
section of the unit file -
See
man systemd.service
for more detail onTimeout*
directives