I have a simple Java application that I need to be running at all time (also to start automatically on server restart).
I have thought on a service wrapper, but the Windows version is paid.
Is there a way that I can configure Tomcat to run a specific class from a project automatically or any other solution that could give the same result?
I think your need is to have an application (whatever web or non web) that starts with tomcat at the same time.
Well, you need to have a simple web application that registers a listener (that listens to the application start event i.e. tomcat start event) and launches your class.
It's very simple in your web.xml you declare a listener like this :
<listener>
<description>application startup and shutdown events</description>
<display-name>ApplicationListener</display-name>
<listener-class>com.myapp.server.config.ApplicationListener</listener-class>
</listener>
And in you ApplicationListener class you implement ServletContextListener interface. Here is an example :
import java.io.File;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
* Class to listen for application startup and shutdown
*
* @author HBR
*
*/
public class ApplicationListener implements ServletContextListener {
private static Logger logger = Logger.getLogger(ApplicationListener.class);
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
logger.info("class : context destroyed");
}
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
ServletContext context = servletContextEvent.getServletContext();
///// HERE You launch your class
logger.info("myapp : context Initialized");
}
}
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