pantominas
pantominas

Reputation: 407

run non web java application on 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?

Upvotes: 8

Views: 6908

Answers (3)

Houcem Berrayana
Houcem Berrayana

Reputation: 3080

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



}

Upvotes: 6

Michael Lloyd Lee mlk
Michael Lloyd Lee mlk

Reputation: 14661

A quick google shows a bunch of options:

Finally if you want it in Tomcat (as part of a web app) then something like Quartz Scheduler.

Upvotes: 0

AlexR
AlexR

Reputation: 115328

Take a look on:

  1. http://wrapper.tanukisoftware.com/doc/english/download.jsp
  2. http://commons.apache.org/daemon/jsvc.html

Both will help you to run java application as a service. If however you want to run couple your application with tomcat you can implement your own simple web application that runs your application. You can use either

  1. servlet that starts on server startup (configure this in web.xml)
  2. HTTP filter
  3. ServletContextListener.

Upvotes: 0

Related Questions