Starting up a background server process when Tomcat starts

[Servlet 2.3] You can implement the ServletContextListener. When a servlet context is initialized/destroyed, the container invokes the callback methods contextInitialized/contextDestroyed.

The following example schedules a Task every 30 seconds.

TaskScheduler.java:

package com.esus.test;
 
import javax.servlet.*;
import java.util.*;
 
public class TaskScheduler implements ServletContextListener {
   private ServletContext context = null;
   private Timer timer = null;
 
   public TaskScheduler() {
   }
 
   public void contextInitialized(ServletContextEvent event) {
      this.context = event.getServletContext();
 
      System.out.println("Context of Web Application has been started!");
 
      MyTask task = new MyTask();
      timer = new Timer();
      timer.schedule(task, 1000, 30000);
 
      //possibility to make TaskScheduler available to servlets/JSP's
      //event.getServletContext().setAttribute("TaskScheduler", this);
   }
 
   public void contextDestroyed(ServletContextEvent event) {
      this.context = null;
 
      if (timer != null) {
         timer.cancel();
      }
      System.out.println("Context of Web Application has been destroyed");
   }
}
 
class MyTask extends TimerTask
{
   public MyTask() {
   } 
 
   public void run() {
      System.out.println("Executing MyTask...");
   }
}

Then you have to refer to this class in web.xml:

<?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">
 
<web-app>
   <listener>
      <listener-class>
         com.esus.test.TaskScheduler
      </listener-class>
   </listener>
   . . .
</web-app>

Notice that TaskScheduler can be made available to servlets/JSP’s by using

   getServletContext().setAttribute