Servlets Servlet中的后台进程
是否可以在servlet中实现后台进程 让我解释一下。 我有一个servlet,它显示一些数据并生成一些报告。 报告的生成意味着数据已经存在,这就是:其他人上传这些数据Servlets Servlet中的后台进程,servlets,process,background,Servlets,Process,Background,是否可以在servlet中实现后台进程 让我解释一下。 我有一个servlet,它显示一些数据并生成一些报告。 报告的生成意味着数据已经存在,这就是:其他人上传这些数据 除了生成报告之外,我还应该实现一种在新数据(上传)到达时发送电子邮件的方法。功能需求不清楚,但要回答实际问题:是的,可以在servletcontainer中运行后台进程 如果您想要应用程序范围的后台线程,请使用来挂接webapp的启动和关闭,并使用来运行它 @WebListener public class Config imp
除了生成报告之外,我还应该实现一种在新数据(上传)到达时发送电子邮件的方法。功能需求不清楚,但要回答实际问题:是的,可以在servletcontainer中运行后台进程 如果您想要应用程序范围的后台线程,请使用来挂接webapp的启动和关闭,并使用来运行它
@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();
}
}
如果您尚未使用Servlet 3.0,因此无法使用@WebListener
,请按如下方式在web.xml
中注册它:
com.example.Config
如果需要会话范围的后台线程,请使用启动和停止它
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.
}
}
在第一次创建和开始时,只需执行以下操作
request.getSession().setAttribute("task", new Task());
谢谢大家!!我想知道这是否应该在请求范围内更好地完成,例如:
public class StartServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getSession().setAttribute("task", new Task());
}
}
这样,当用户离开页面时,进程将停止。感谢您的重播。很抱歉我的要求是实现一种在上传某些数据(新数据加载到DB中)时发送电子邮件(警报)的方法。我曾想过通过修改现有的web应用程序来实现这种机制,创建对新数据进行轮询的后台进程。数据由我不管理的其他应用程序加载。Servlet容器是Tomcat。谢谢你的回答为什么你不直接在DB中更新数据的代码之后写这个?因为我没有访问加载数据的应用程序:它是由其他人管理和开发的,我无法访问。这个线程没有阻塞,是吗?