背景
在使用scheduledExecutorService.scheduleAtFixedRate
()
时发现定时任务不知道在什么时候就停了,因为有了解到scheduledExecutorService
会因为出现异常而停止定时任务,所以我特地加了try/catch
捕获异常,代码大致如下:
scheduledExecutorService.scheduleAtFixedRate(() -> {
try {
service.backupData(1);
} catch (Exception e) {
System.out.println("This is Exception!");
log.error(e.getMessage());
System.out.println("=========================");
}, 1, 10, TimeUnit.SECONDS);
好奇怪= =于是又去仔细翻阅了官方文档里面的记录
官网说明
Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is executions will commence after
initialDelay
theninitialDelay+period
, theninitialDelay + 2 * period
, and so on. If any execution of the task encounters an exception, subsequent executions are suppressed. Otherwise, the task will only terminate via cancellation or termination of the executor. If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.
翻并分析下
创建并执行一个周期性的动作,该动作在给定的初始延迟(initialDelay
)后,会先执行一下,随后在给定的周期内不断循环执行;也就是说,执行将在initialDelay
之后开始第一次执行,然后是 initialDelay+period
,然后是 initialDelay + 2 * period
,依此类推。 如果任务的任何执行遇到异常,则后续执行将被抑制。 否则,任务只会通过取消或终止执行者来终止。 如果此任务的任何执行时间超过其周期,则后续执行可能会延迟开始,但不会同时执行。
好像官网提供的只有报异常这一种情况,定时任务会终止,可是我已经catch Exception叻
到底为啥,,知道我查日志的时候忽然发现Java可不只有Exception,他还有Error!!
由于Exception和Error都继承了Throwable,所以我改掉了Exception,换成了Throwable
参考:
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledExecutorService.html
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/135447.html