The functional requirement is unclear, but to answer the actual question: yes, it's possible to run a background process in servletcontainer.
If you want an applicationwide background thread, use ServletContextListener to hook on webapp's startup and shutdown and use ExecutorService to run it.
@WebListener
public class Config implements ServletContextListener {
private ExecutorService executor;
public void contextInitialized(ServletContextEvent event) {
executor = Executors.newSingleThreadExecutor();
executor.submit(new Task()); // Task should implement Runnable.
}
public void contextDestroyed(ServletContextEvent event) {
executor.shutdown();
}
}
If you're not on Servlet 3.0 yet and thus can't use @WebListener
, register it as follows in web.xml
instead:
<listener>
<listener-class>com.example.Config</listener-class>
</listener>
If you want a sessionwide background thread, use HttpSessionBindingListener to start and stop it.
public class Task extends Thread implements HttpSessionBindingListener {
public void run() {
while (true) {
someHeavyStuff();
if (isInterrupted()) return;
}
}
public void valueBound(HttpSessionBindingEvent event) {
start(); // Will instantly be started when doing session.setAttribute("task", new Task());
}
public void valueUnbound(HttpSessionBindingEvent event) {
interrupt(); // Will signal interrupt when session expires.
}
}
On first creation and start, just do
request.getSession().setAttribute("task", new Task());