以下是一种方法。一个servlet上下文侦听器添加到您的web.xml
,例如:
<listener>
<listener-class>com.example.BackgroundServletContextListener</listener-class>
</listener>
然后创建一个类来管理您的后台服务。在这个例子中,我使用单线程ScheduledExecutorService
安排它每5分钟运行:
public class BackgroundServletContextListener implements ServletContextListener {
private ScheduledExecutorService executor;
private BackgroundService service;
public void contextInitialized(ServletContextEvent sce) {
service = new BackgroundService();
// setup single thread to run background service every 5 minutes
executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(service, 0, 5, TimeUnit.MINUTES);
// make the background service available to the servlet context
sce.getServletContext().setAttribute("service", service);
}
public void contextDestroyed(ServletContextEvent sce) {
executor.shutdown();
}
}
public class BackgroundService implements Runnable {
public void run() {
// do your background processing here
}
}
如果您需要从Web请求访问BackgroundService
,您可以通过ServletContext
访问它。例如。:
ServletContext context = request.getSession().getServletContext();
BackgroundService service = (BackgroundService) context.getAttribute("service");
Spring的IOC和自动装配是不是你想要的?它可以让你创建任何其他类可以到达的单身人士。 – 2011-04-10 01:11:03
我的猜测是他目前的项目中没有Spring。恕我直言,只为单身人士添加Spring将是一个矫枉过正的行为。 – 2011-04-10 02:12:47