以下是一種方法。一個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