Scheduling Function or Repeating Job in Tomcat
Repeating jobs in tomcat can be created by creating a listener which will get started when tomcat is started or new war is deployed and destroyed when tomcat is shutdown.We can take advantage of thread and infinite loop in which we can do our repetitive work and then wait for specified time and loop again.
This example have been tested in tomcat 8.5.23 and will be applicable for other application server as well.
web.xml
<listener>
<listener-class>com.test.api.util.NotificationListener</listener-class>
</listener> Java class
package com.test.api.util;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class NotificationListener implements ServletContextListener {
private Thread t = null;
private ServletContext context;
public void contextInitialized(ServletContextEvent contextEvent) {
t = new Thread(){
//repeating task
public void run(){
try {
while(true){
// do all you repeating jobs here.
// Example 1. sending reports every 5 mins. 2. sending notifications 3. db cleanup etc.
Thread.sleep(1000*60*5); // thread waits for 5 mins.
}
} catch (InterruptedException e) {}
}
};
t.start(); // starting the thread
context = contextEvent.getServletContext();
// context values can be set as well as shown below
context.setAttribute("TEST_VARIABLE", "VALUE");
}
public void contextDestroyed(ServletContextEvent contextEvent) {
// context is destroyed interrupts the thread
t.interrupt();
}
}
NOTE
1. you can use producer and consume problem approach as well and start them in constructor.