1. 程式人生 > >[JAVA學習筆記-73]Executors的兩種定時執行機制

[JAVA學習筆記-73]Executors的兩種定時執行機制

ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)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.
【以period指定的時長為週期執行任務;如果遇到異常,則後續的執行被壓制不執行;如果任務的執行時間超過了period,後續的執行會延遲啟動,不會併發執行,執行緒池會連續執行被積壓的任務(此時rate)實際上是不保證的,例如因為某次執行超時積壓了3次執行任務,則此超時任務完成後,執行緒池可能會連續執行3次(假設正常是1s執行一次)從而“趕上”步伐,保證後續的執行正常進行。】ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)
Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next. 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.
【保證兩次任務執行之間的間隔為delay指定的時長;如果執行的任務出現異常,後續的任務均會被壓制住不執行;正常情況下,只有cancel或者shutdown操作才會停止執行。】