java – 如何使用ScheduledExecutorService重新安排任务?

我在
java docs:
ScheduledAtFixedRate中看到了这一点

If any execution of the task
encounters an exception,subsequent
executions are suppressed

我不希望在我的应用程序中发生这种情况.即使我看到一个异常,我总是希望随后的执行发生并继续.如何从ScheduledExecutorService获取此行为.

解决方法

使用try / catch环绕Callable.call方法或Runnable.run方法

例如:

public void run()
{
    try
    {
        // ... code
    }
    catch(final IOException ex)
    {
        // handle it
    }
    catch(final RuntimeException ex)
    {
        // handle it
    }
    catch(final Exception ex)
    {
        // handle it
    }
    catch(final Error ex)
    {
        // handle it
    }
    catch(final Throwable ex)
    {
        // handle it
    }
}

注意,除了编译器告诉你的东西以外,捕获任何东西(我的示例中的IOException)不是一个好主意,但有一些时候,这听起来像是其中之一,如果你正确处理它,它可以解决.

记住,像错误这样的事情是非常糟糕的 – 虚拟机内存不足等等,所以要小心你如何处理它们(这就是为什么我把它们分离成自己的处理程序,而不是只是做catch(最后的Throwable ex)和没有其他).

dawei

【声明】:淮南站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。