How to stop threads when undeploying a Java EE application? [duplicate]
Rather use ScheduledExecutorService#scheduleAtFixedRate()
instead of the old fashioned Thread#sleep()
. You can use ServletContextListener
to run it on webapp's startup and stop it on webapp's shutdown.
@WebListenerpublic class Config implements ServletContextListener { private ScheduledExecutorService scheduler; @Override public void contextInitialized(ServletContextEvent event) { scheduler = Executors.newSingleThreadScheduledExecutor(); scheduler.scheduleAtFixedRate(new Task(), 0, 1, TimeUnit.MINUTES); // Schedule to run every minute. } @Override public void contextDestroyed(ServletContextEvent event) { scheduler.shutdown(); // Important! This stops the thread. }}
Where Task
can look like this:
public class Task implements Runnable { @Override public void run() { log(something); }}
If your environment doesn't support Servlet 3.0 @WebListener
, then register it as follows in web.xml
to get it to run:
<listener> <listener-class>com.example.Config</listener-class></listener>