Lovepreet Singh Lovepreet Singh - 4 months ago 21x
Linux Question

How to trigger a custom script to run whenever a specific systemd service restarts

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

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.

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


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.

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

EDIT: 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
ExecStartPre=/home/meuh/myscripttorun  some pre args here
ExecStartPost=/home/meuh/myscripttorun some post args here

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