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-app xmlns:xsi="" xmlns="" xmlns:web="" xsi:schemaLocation="" id="WebApp_ID" version="2.5">



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(){
            public void run(){                
                try {
                        System.out.println("Thread running every second");
                } catch (InterruptedException e) {}
        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