天天看點

ScheduledExecutorService與Timer的方法比較

ScheduledExecutorService與Timer都有scheduleAtFixedRate方法

一、相同名稱的方法

scheduleAtFixedRate

ScheduledExecutorService 的 scheduleAtFixedRate(Runnable command,long initialDelay,long period1,TimeUnit unit) 與Timer 的 scheduleAtFixedRate(TimerTask task, long delay, long period2) 功能是一樣的:

在initialDelay/delay後第一次執行command/task;

然後在第一次開始執行command/task的時間點開始算,period1/period2後第二次執行command/task;

然後在第二次開始執行command/task的時間點開始算,period1/period2後第三次執行command/task;

然後在第三次開始執行command/task的時間點開始算,period1/period2後第四次執行command/task;

...

...

...

如果delay/period後的時間點上一次的command/task還沒有執行完,那麼會等到上一次的執行完,才會開始下一次的執行。

二、ScheduledExecutorService的方法

scheduleWithFixedDelay(Runnable command,long initialDelay,long delay,TimeUnit unit)功能為:

在initialDelay後第一次執行command;

然後在第一次結束執行command的時間點開始算,delay後第二次執行command;

然後在第二次結束執行command的時間點開始算,delay後第三次執行command;

然後在第三次結束執行command的時間點開始算,delay後第四次執行command;

...

...

...