背景
前一段時(shí)間有個(gè)任務(wù)是需要做一個(gè)每隔固定時(shí)長執(zhí)行一次的服務(wù)(就是個(gè)定時(shí)任務(wù)),結(jié)合了下以往的學(xué)習(xí),決定采用ScheduledExecutorService來實(shí)現(xiàn)
但是在使用scheduledExecutorService.scheduleAtFixedRate()函數(shù)時(shí),發(fā)現(xiàn)定時(shí)任務(wù)不知道在什么時(shí)候就停了,因?yàn)橛浀弥傲私獾竭^scheduledExecutorService會(huì)因?yàn)槌霈F(xiàn)異常而停止定時(shí)任務(wù),所以我特地加了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);
但服務(wù)還是會(huì)不知道什么時(shí)候就停止了(-?-;奇怪= =
于是又去仔細(xì)翻閱了官方文檔里面的記錄
官網(wǎng)說明

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.
翻并分析下
創(chuàng)建并執(zhí)行一個(gè)周期性的動(dòng)作,該動(dòng)作在給定的初始延遲(initialDelay)后,會(huì)先執(zhí)行一下,隨后在給定的周期內(nèi)不斷循環(huán)執(zhí)行;也就是說,執(zhí)行將在initialDelay之后開始第一次執(zhí)行,然后是 initialDelay+period,然后是 initialDelay + 2 * period,依此類推。 如果任務(wù)的任何執(zhí)行遇到異常,則后續(xù)執(zhí)行將被抑制。 否則,任務(wù)只會(huì)通過取消或終止執(zhí)行者來終止。 如果此任務(wù)的任何執(zhí)行時(shí)間超過其周期,則后續(xù)執(zhí)行可能會(huì)延遲開始,但不會(huì)同時(shí)執(zhí)行。
好像官網(wǎng)提供的只有報(bào)異常這一種情況,定時(shí)任務(wù)會(huì)終止,可是我已經(jīng)catch Exception叻
到底為啥,,知道我查日志的時(shí)候忽然發(fā)現(xiàn)Java可不只有Exception,他還有Error!!
由于Exception和Error都繼承了Throwable,所以我改掉了Exception,換成了Throwable。
當(dāng)時(shí)到現(xiàn)在也有個(gè)把月了,目前為止該問題沒有再出現(xiàn)過~撒花??????
官方參考
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledExecutorService.html