tags:

views:

76

answers:

2

i want a thread to start automaticalyy when my application on tmocat is started. How do i do that.Do i have to add something to web.xml??

+2  A: 

You may do this with a SerlvetContextListener.

Create a class that implements the ServletContextListener interface:

import javax.servlet.*;
import javax.servlet.http.*;

public class ApplicationStartup implements ServletContextListener {

  public void contextInitialized(ServletContextEvent event) {
    // Do work here...
    // new Thread().start(); etc...
  }

  public void contextDestroyed(ServletContextEvent event)
  {
     // Stop work here if required
  }
}

Add your class to the web.xml file:

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/j2ee/dtds/web-app_2.3.dtd"&gt;

<web-app>

  <!-- Listeners -->
  <listener>
    <listener-class>ApplicationStartup</listener-class>
  </listener>

</web-app>
CharlieWhiskey
+1  A: 

It is not a good idea to start your own threads in Tomcat or any other JEE container (many related questions here in SO). You will be better off using Quartz scheduler.

kgiannakakis