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

编程入门 行业动态 更新时间:2024-10-18 12:23:30
本文介绍了如何使用ScheduledExecutorService重新安排任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

如果执行任务遇到异常,则后续执行被禁止

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

我不希望在我的应用程序中发生这种情况。即使我看到异常,我也总是希望后续执行发生并继续。如何从 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重新安排任务?

本文发布于:2023-07-14 10:01:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1104038.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   ScheduledExecutorService

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!