Article updated on

Como crear una tarea, Cron Job o nuevo proceso en Tomcat

Para esto puedes usar frameworks programadores de tareas como quartz, pero si quieres algo más sencillo puedes lanzar un hilo que se inicia y termina cuando el contexto se inicia, ya sea cuando el servidor se inicia o cuando se despliega o se quita la aplicación.

Crear hilos en tomcat puede ser arriesgado, demasiados abiertos pueden tumbarlo. Puedes limitar la cantidad de hilos con el atributo maxThreads.

*Este ejemplo funciona con Tomcat pero podría funcionar con cualquier servidor de aplicaciones.

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>
 

 

Ejemplo

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("Se ejecuta una vez cada segundo");
                        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) {
        // si se destruye el contexto se interrumpe el thread
        t.interrupt();
    }            
}