使用ScheduledExecutorService重新安排任务

使用ScheduledExecutorService重新安排任务

本文介绍了如何使用ScheduledExecutorService重新安排任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在java文档中看到了这一点:,它说

I saw this in the java docs: ScheduledAtFixedRate, it says

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

I don't want this to happen in my application. Even if I see an exception I would always want the subsequent executions to occur and continue. How can I get this behavior from ScheduledExecutorService.

推荐答案

围绕Callable .call方法或带有try / catch的Runnable.run方法......

Surround the Callable.call method or the Runnable.run method with a try/catch...

例如:

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)不是一个好主意,但有时候,这听起来像其中之一,它可以工作如果你正确处理它,请输出。

Note that catching anything other than what the compiler tells you too (the IOException in my sample) isn't a good idea, but there are some times, and this sounds like one of them, that it can work out if you handle it properly.

请记住像错误这样的东西非常糟糕 - 虚拟机内存不足等等......所以要小心你如何处理它们(这就是为什么我将它们分成自己的处理程序而不仅仅是捕获(最终的Throwable ex)而不是其他任何东西)。

Remember that things like Error are very bad - the VM ran out of memory etc... so be careful how you handle them (which is why I separated them out into their own handlers rather than just doing catch(final Throwable ex) and nothing else).

这篇关于如何使用ScheduledExecutorService重新安排任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 06:38