I would like to know how to run a shell script on Tomcat startup, that is when catalina.log prints \"INFO: Server startup in xxx ms\"
Thanks in advance, bye
find tomcat startup script (in /etc/init.d/
maybe tomcat7
) and write call-to-your-script in appropriate place at start
block.
At Tomcat 7, you can accomplish that through a custom listener in the server.xml file at tomcat's configuration:
<?xml version="1.0" encoding="utf-8"?>
<Server port="8005" shutdown="SHUTDOWN">
<Listener className="your.domain.CustomEventHookListener" />
<Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
<Listener className="org.apache.catalina.core.JasperListener" />
<Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
<Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
<Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />
<Service name="Catalina">
<Connector port="8888" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
<Engine name="Catalina" defaultHost="default">
<Host name="default"
appBase="webapps"
unpackWARs="false"
autoDeploy="false">
<Context path="" docBase="/opt/www/application">
</Context>
</Host>
</Engine>
</Service>
</Server>
CustomEventHootListener.java:
package your.domain;
import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleEvent;
import org.apache.catalina.LifecycleListener;
public class CustomEventHookListener implements LifecycleListener {
@Override
public void lifecycleEvent(LifecycleEvent arg0) {
Lifecycle lifecycle = arg0.getLifecycle();
if (lifecycle == null) {
return;
}
String type = arg0.getType();
if (type == null) {
return;
}
String stateName = lifecycle.getStateName();
if (stateName == null) {
return;
}
if (type.equals("after_start") && stateName.equals("STARTED")) {
startPostInitScript();
}
}
private void startPostInitScript() {
// Non-blocking please.
Thread t = new Thread() {
@Override
public void run() {
try {
super.run();
String script = "/path/to/your-script.sh";
// inheritIO to output things to JVM.
new ProcessBuilder().command(script).inheritIO().start().waitFor();
} catch (Throwable e) {
e.printStackTrace();
}
}
};
t.setDaemon(true);
t.start();
}
}
You can see a functional example at https://github.com/Valemobi/tomcat-events-hook