如何触发自定义脚本以在特定的systemd服务重新启动时运行 [英] How to trigger a custom script to run whenever a specific systemd service restarts

查看:707
本文介绍了如何触发自定义脚本以在特定的systemd服务重新启动时运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何安排一个自定义脚本在每次重新启动服务时运行。

I wish to know how can I schedule a custom script to run whenever I restart a service.

我的用例是,我必须运行几个命令重新启动我的Tomcat服务。我想知道是否有一种方式,我可以编写一个脚本,并计划它运行时,每当我重新启动Tomcat服务。

My use case is that I have to run several commands whenever I restart my Tomcat Service. I want to know if there is a way I can write a script and schedule it to run whenever I restart the Tomcat service.

我已经设置tomcat脚本作为systemd服务。我使用Cent OS 7 x64。

I have setup the tomcat script as a systemd service. I am using Cent OS 7 x64.

推荐答案

我已经能够通过创建另一个服务并结合Tomcat服务启动停止在新服务。新服务作为一个包装服务,首先启动tomcat,然后执行我们需要运行的命令,一旦tomcat启动。

I have been able to achieve this by creating another service and incorporating the Tomcat service's start stop in the new service. The new service acts as a wrapper service which first starts tomcat and then executes the commands that we need to run as soon as tomcat starts.

然后在停止时,它停止tomcat并运行清理命令。

Then while stopping, it stops tomcat and runs clean up commands.

编辑:我发现了另一种方式在unix& linux stackexchange。
只需在/ etc中创建一个新的systemd .service文件,该文件包含和覆盖/ lib中的一部分。例如,创建/etc/systemd/system/tomcat.service以包含

I found another way of doing this on unix & linux stackexchange. Simply create an new systemd .service file in /etc which includes and overrides part of the one in /lib. For example, create /etc/systemd/system/tomcat.service to contain

.include /lib/systemd/system/tomcat.service
[Service]
ExecStartPre=/home/meuh/myscripttorun  some pre args here
ExecStartPost=/home/meuh/myscripttorun some post args here

任何ExecStartPre行都将在ExecStart行之前执行,类似地,任何ExecStartPost将在tomcat启动后运行。

Any ExecStartPre lines will be executed before the ExecStart line, and similarly any ExecStartPost will run after tomcat has started.

这篇关于如何触发自定义脚本以在特定的systemd服务重新启动时运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆