【填坑向】记一次使用ScheduledExecutorService.scheduleAtFixedRate()的坑

有目标就不怕路远。年轻人.无论你现在身在何方.重要的是你将要向何处去。只有明确的目标才能助你成功。没有目标的航船.任何方向的风对他来说都是逆风。因此,再遥远的旅程,只要有目标.就不怕路远。没有目标,哪来的劲头?一车尔尼雷夫斯基

导读:本篇文章讲解 【填坑向】记一次使用ScheduledExecutorService.scheduleAtFixedRate()的坑,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

背景

在使用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);

好奇怪= =于是又去仔细翻阅了官方文档里面的记录

官网说明

【填坑向】记一次使用ScheduledExecutorService.scheduleAtFixedRate()的坑

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 then initialDelay+period, then initialDelay + 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

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!