Tomcat servlet 应用程序的后台线程 [英] Background Thread for a Tomcat servlet app

查看:22
本文介绍了Tomcat servlet 应用程序的后台线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆