Article updated on

How to Create a Task(or Cron Job) in Tomcat Example

To do this you can take advantage of schedulers such us quartz, but it you don't need anything as powerful as that you can create a new thread that starts when the server starts.

Creating new threads in a web server can be risky. If too many threads are being kept open you can cause the application server or web container to shutdown. In Tomcat you can limit the amount of threads with the maxThreads attribute.

In this example a Listener is used so when the context is created or destroyed (war deployed or removed) all threads created will be removed from the server.

*This example was tested in Tomcat but can work in any other application server or web container.

web.xml

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <listener>
    <listener-class>
            com.test.ListenerTaskExample
        </listener-class>
  </listener>
</web-app>
 

 

Example

package com.test;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ListenerTaskExample implements ServletContextListener {
    private Thread t = null;
    private ServletContext context;
    public void contextInitialized(ServletContextEvent contextEvent) {
        t =  new Thread(){
            //task
            public void run(){                
                try {
                    while(true){
                        System.out.println("Thread running every second");
                        Thread.sleep(1000);
                    }
                } catch (InterruptedException e) {}
            }            
        };
        t.start();
        context = contextEvent.getServletContext();
        // you can set a context variable just like this
        context.setAttribute("TEST", "TEST_VALUE");
    }
    public void contextDestroyed(ServletContextEvent contextEvent) {
        // context is destroyed interrupts the thread
        t.interrupt();
    }            
}