ScheduledExecutorService 設計思想
ScheduledExecutorService,是基于線程池設計的定時任務類,每個調度任務都會分配到線程池中的一個線程去執行,也就是說,任務是并發執行,互不影響。
需要注意,只有當調度任務來的時候,ScheduledExecutorService才會真正啟動一個線程,其余時間ScheduledExecutorService都是出于輪詢任務的狀態。
1、線程任務
class MyScheduledExecutor implements Runnable {
private String jobName;
MyScheduledExecutor() {
}
MyScheduledExecutor(String jobName) {
this.jobName = jobName;
}
@Override
public void run() {
System.out.println(jobName + " is running");
}
}
2、定時任務
public static void main(String[] args) {
ScheduledExecutorService service = Executors.newScheduledThreadPool(10);
long initialDelay = 1;
long period = 1;
// 從現在開始1秒鐘之后,每隔1秒鐘執行一次job1
service.scheduleAtFixedRate(new MyScheduledExecutor("job1"), initialDelay, period, TimeUnit.SECONDS);
service.scheduleWithFixedDelay(new MyScheduledExecutor("job2"), initialDelay, period, TimeUnit.SECONDS);
}
ScheduledExecutorService 中兩種最常用的調度方法 ScheduleAtFixedRate 和 ScheduleWithFixedDelay。ScheduleAtFixedRate 每次執行時間為上一次任務開始起向后推一個時間間隔,即每次執行時間為 :initialDelay, initialDelay+period, initialDelay+2period, …;ScheduleWithFixedDelay 每次執行時間為上一次任務結束起向后推一個時間間隔,即每次執行時間為:initialDelay, initialDelay+executeTime+delay, initialDelay+2executeTime+2*delay。由此可見,ScheduleAtFixedRate 是基于固定時間間隔進行任務調度,ScheduleWithFixedDelay 取決于每次任務執行的時間長短,是基于不固定時間間隔進行任務調度。