1. ScheduledThreadPoolExecutor線程池
2. SpringBoot2.X整合定時線程池(ScheduledThreadPoolExecutor)

image.png
1. 線程池的構(gòu)造方法
ScheduledThreadPoolExecutor最全構(gòu)造方法:
public ScheduledThreadPoolExecutor(int corePoolSize,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue(), threadFactory, handler);
}
我們自定義ScheduledThreadPoolExecutor線程池的時候,可以設(shè)置核心線程數(shù)、線程工廠、拒絕策略。
阻塞隊列默認使用的是DelayedWorkQueue(延遲隊列,是一個優(yōu)先級隊列,本質(zhì)上就是堆)。保證每次出隊時一定是當(dāng)前隊列中執(zhí)行時間最靠前的。
使用Executors靜態(tài)類快速創(chuàng)建ScheduledThreadPoolExecutor:
Executors.newScheduledThreadPool(3);
2. 添加延時任務(wù)
因為ScheduledThreadPoolExecutor實現(xiàn)了ExecutorService接口,那么他也能夠使用通用的executor或者submit提交任務(wù),最終調(diào)用schedule方法,默認馬上執(zhí)行一次。若需要延遲執(zhí)行,可直接使用schedule方法,傳遞時間參數(shù)。
//延遲delay時間后,執(zhí)行任務(wù)。因為傳入的是Runnable,故get()方法獲取的為null
public ScheduledFuture<?> schedule(Runnable command,
long delay, TimeUnit unit);
//帶返回值的延遲任務(wù)
public <V> ScheduledFuture<V> schedule(Callable<V> callable,
long delay, TimeUnit unit);
3. 添加周期任務(wù)
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
long initialDelay,
long period,
TimeUnit unit);
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
long initialDelay,
long delay,
TimeUnit unit);
- scheduleAtFixedRate:按照固定的頻率執(zhí)行,不受執(zhí)行時長影響,若發(fā)生misfire(即上一次執(zhí)行時長大于period),則下一次任務(wù)立即執(zhí)行。
- scheduleWithFixedDelay:任務(wù)執(zhí)行完畢后,按照固定的delay時間間隔執(zhí)行。
4. 如何終止周期任務(wù)
方式一:拋出異常,即可終止定時任務(wù)。
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);
scheduledExecutorService.scheduleWithFixedDelay(() -> {
System.out.println("start scheduled...");
throw new RuntimeException();
}, 0, 1000, TimeUnit.MILLISECONDS);
方式二:調(diào)用Future的cancal方法
future.cancel(false);