怎么配置一个systemd服务以便在系统关闭时执行命令或者脚本

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 - 

English 

环境

  • 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= and DefaultTimeoutStopSec= from /etc/systemd/system.conf

  • To allow the commands to take more than 90sec, add TimeoutSec=3min or TimeoutSec=0 (disabled) to the [Service] section of the unit file

  • See man systemd.service for more detail on Timeout* directives

     

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值