Servlet background process

Is it possible to implement a background process in a servlet ??

Let me explain. I have a servlet that shows some data and generates some reports. Report generation implies that the data is already present, and that’s it: someone else is loading this data.

In addition to generating reports, I have to implement a way to send emails upon arrival of new data (uploaded).

+4
source share
2 answers

The functional requirement is unclear, but to answer the actual question: yes, it is possible to start the background process in the servletcontainer.

If you want to use the background thread in the application, use the ServletContextListener to connect to the start up and shutdown of the webapp and use the ExecutorService to start 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 are not already on Servlet 3.0 and therefore cannot use @WebListener , register it as follows web.xml :

 <listener> <listener-class>com.example.Config</listener-class> </listener> 

If you want to use a common background thread, use the 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. } } 

The first time you create and run, simply

 request.getSession().setAttribute("task", new Task()); 
+17
source

Thanks! I was wondering if it is better to do this inside the request area, for example:

 public class StartServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getSession().setAttribute("task", new Task()); } } 

Thus, the process stops when the user leaves the page.

0
source

Source: https://habr.com/ru/post/1313382/


All Articles