TimerTask停止在Tomcat Servlet中运行的原因是什么? [英] What can be the reasons for a TimerTask to stop running in a Tomcat Servlet

查看:156
本文介绍了TimerTask停止在Tomcat Servlet中运行的原因是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怀疑异常会导致TimerTask停止运行,在这种情况下,我很可能需要第二个时间任务来监控第一个仍然在运行吗?

I suspect an exception could make the TimerTask stop running in which case I most likely need a second timetask to monitor that the first is still running?

更新

感谢您的回答。我继承了这段代码,所以有点无知......

Thanks for the answers. I had inherited this code so a bit ignorant...

我刚看到如果我在工作中抛出未捕获的异常,TimerThread就会永远无法运行。

I just saw that if I throw an uncaught exception in my job the TimerThread ceases to run forever.

的运行方法TimerThread 显示如果抛出异常,我的预定线程永远不会再次运行。

Run method of TimerThread showed that if an exception is thrown, my scheduled thread never runs again.

public void run() {
    try {
        mainLoop();
    } finally {
        // Someone killed this Thread, behave as if Timer cancelled
        synchronized(queue) {
            newTasksMayBeScheduled = false;
            queue.clear();  // Eliminate obsolete references
        }
    }
}

stacktrace的结尾将是:

The end of the stacktrace will be:

at java.util.TimerThread.mainLoop(Timer.java:512)
at java.util.TimerThread.run(Timer.java:462)

所以临时解决方案是抓住一切......长期解决方案是按照BalusC的说法进行更好的调度。

So temp solution is to catch EVERYTHING... longer term solution is to move to better scheduling as BalusC states.

推荐答案

当抛出未捕获的异常时TimerTasks死掉(它是否在tomcat中运行是无关的)。解决此问题的最简单方法是在run方法中捕获RuntimeException,并记录&继续,如果这是你想要的。

TimerTasks die when an uncaught exception is thrown (whether it's running in tomcat or not is unrelated). The easiest way to resolve this is to catch RuntimeException in your run method, and log & continue if that's what you want.

同样建议捕获Throwables并在重新抛出之前记录它,以便在日志中看到堆栈跟踪,如下所示:

It's also advisable to catch Throwables as well and log it before you rethrow it so that you can see the stacktrace in your logs, like this:

    try{
        doRun();
    }catch (RuntimeException e){
        logger.error("Uncaught Runtime Exception",e);
        return; // Keep working
    }catch (Throwable e){
        logger.error("Unrecoverable error",e);
        throw e;
    }

这篇关于TimerTask停止在Tomcat Servlet中运行的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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