Tomcat servlet应用程序的后台线程 [英] Background Thread for a Tomcat servlet app
问题描述
我对Tomcat不太熟悉,在我看来它基本上被抽象为cgi服务器,可以在调用之间保存JVM - 我知道它可以做更多的事情。
I am not very familiar with Tomcat, in my head it is basically abstracted as a cgi server that saves the JVM between calls -- I know it can do a lot more than that, though.
我正在寻找一种在Tomcat服务器启动时启动后台线程的方法,它会定期更新服务器上下文(在我的特定情况下)这是一个线程,它从一些其他服务中侦听心跳并更新可用性信息,但可以想象这有多种用途)。
I am looking for a way to launch a background thread when a Tomcat server starts, which would periodically update the Server Context (in my particular case this is a thread that listens to heartbeats from some other services and updates availability information, but one can imagine a variety of uses for this).
有没有一种标准方法可以做到这一点?启动和更新/查询Context?
Is there a standard way to do this? Both the launching, and the updating/querying of the Context?
任何指向相关文档和/或代码示例的指针都将非常感激。
Any pointers to the relevant documentation and/or code samples would be much appreciated.
推荐答案
如果要在部署WAR时启动线程,可以在web.xml中定义上下文侦听器:
If you want to start a thread when your WAR is deployed, you can define a context listener within the web.xml:
<web-app>
<listener>
<listener-class>com.mypackage.MyServletContextListener</listener-class>
</listener>
</web-app>
然后实现这样的类:
public class MyServletContextListener implements ServletContextListener {
private MyThreadClass myThread = null;
public void contextInitialized(ServletContextEvent sce) {
if ((myThread == null) || (!myThread.isAlive())) {
myThread = new MyThreadClass();
myThread.start();
}
}
public void contextDestroyed(ServletContextEvent sce){
try {
myThread.doShutdown();
myThread.interrupt();
} catch (Exception ex) {
}
}
}
这篇关于Tomcat servlet应用程序的后台线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!