Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

run non web java application on tomcat

Tags:

java

tomcat

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?

like image 248
pantominas Avatar asked Feb 21 '13 09:02

pantominas


1 Answers

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");
    }



}
like image 188
Houcem Berrayana Avatar answered Sep 28 '22 16:09

Houcem Berrayana