I am not very familiar with Tomcat, in my head it is basically abstracted as a cgi server that saves the JVM between calls -- I know it can do a lot more than that, though.
I am looking for a way to launch a background thread when a Tomcat server starts, which would periodically update the Server Context (in my particular case this is a thread that listens to heartbeats from some other services and updates availability information, but one can imagine a variety of uses for this).
Is there a standard way to do this? Both the launching, and the updating/querying of the Context?
Any pointers to the relevant documentation and/or code samples would be much appreciated.
If you want to start a thread when your WAR is deployed, you can define a context listener within the web.xml:
<web-app> <listener> <listener-class>com.mypackage.MyServletContextListener</listener-class> </listener> </web-app>
Then implement that class something like:
public class MyServletContextListener implements ServletContextListener { private MyThreadClass myThread = null; public void contextInitialized(ServletContextEvent sce) { if ((myThread == null) || (!myThread.isAlive())) { myThread = new MyThreadClass(); myThread.start(); } } public void contextDestroyed(ServletContextEvent sce){ try { myThread.doShutdown(); myThread.interrupt(); } catch (Exception ex) { } } }
I am looking for a way to launch a background thread when a Tomcat server starts
I think you are looking for a way to launch a background thread when your web application is started by Tomcat.
This can be done using a ServletContextListener. It is registered in web.xml and will be called when your app is started or stopped. You can then created (and later stop) your Thread, using the normal Java ways to create a Thread (or ExecutionService).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With