springboot-如何配置線程池實現(xiàn)定時任務(wù)
一、步驟概覽
二、步驟說明
1.封裝自定義線程池
封裝自定義線程池類是為了在線程執(zhí)行完畢后,我們檢查是否存在異常,如果存在異常,日志打印詳細異常信息,這樣可以可以幫助我們及時發(fā)現(xiàn)和解決問題。
JDK 默認提供的定時調(diào)度線程池類是
ScheduledThreadPoolExecutor,我們只需要繼承它并重寫它的 afterExecute 方法,添加異常日志打印的邏輯。
- MyScheduledThreadPoolExecutor
public class MyScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor {
private Logger log = LoggerFactory.getLogger(MyScheduledThreadPoolExecutor.class);
public MyScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory factory) {
super(corePoolSize, factory);
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
// 打印異常信息
this.printException(r, t);
}
public void printException(Runnable r, Throwable t) {
// 判斷 r 是 Future 實例并且已經(jīng)完成執(zhí)行的情況下,獲取它的執(zhí)行結(jié)果,并檢查是否有異常拋出
if (t == null && r instanceof Future<?>) {
try {
Future<?> future = (Future<?>) r;
if (future.isDone()) {
future.get();
}
} catch (CancellationException ce) {
t = ce;
} catch (ExecutionException ee) {
t = ee.getCause();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
if (t != null) {
log.error(t.getMessage(), t);
}
}
}
2.定義調(diào)度配置
創(chuàng)建 ScheduleConfig 類,用于配置定時調(diào)度的執(zhí)行器。代碼概覽如圖所示:
① 創(chuàng)建定時調(diào)度線程池
使用自定義封裝的線程池類,創(chuàng)建線程池,指定線程池創(chuàng)建線程名前綴,并將其設(shè)置成應(yīng)用程序的守護線程。
- ScheduleConfig#taskExecutor
@Bean(destroyMethod="shutdown")
public ExecutorService taskExecutor() {
ThreadFactory factory = new BasicThreadFactory.Builder()
.namingPattern("schedule-pool-%d")
.daemon(true)
.build();
return new MyScheduledThreadPoolExecutor(10, factory);
}
② 設(shè)置任務(wù)調(diào)度器
實現(xiàn) SchedulingConfigurer 接口,重寫 configureTasks 方法,允許我們對任務(wù)調(diào)度進行自定義配置,這邊我們將我們自定義創(chuàng)建的線程池設(shè)置成任務(wù)調(diào)度器。
- ScheduleConfig#configureTasks
@Configuration
public class ScheduleConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
// 自定義線程池作為調(diào)度器
taskRegistrar.setScheduler(taskExecutor());
}
}
3.啟用調(diào)度
在應(yīng)用啟動類上添加注解 `@EnableScheduling`,用于啟用定時調(diào)度,操作如圖所示:
4.注解標(biāo)記調(diào)度策略
在我們需要定時執(zhí)行的方法上使用相關(guān)注解,標(biāo)記其調(diào)度策略。
①.固定時間執(zhí)行
如果需要在固定的時間點執(zhí)行任務(wù),可以使用 @Scheduled(cron = "表達式") 注解來指定 cron 表達式,如下所示:
@Component
public class MyTask {
@Scheduled(cron = "0 0 12 * * ?")
public void runTask() {
// 在每天中午 12 點執(zhí)行任務(wù)
}
}
其中 cron 表達式使用說明如下表格所示
位數(shù) | 字段 | 允許值 |
1 | 秒 | 0-59 |
2 | 分鐘 | 0-59 |
3 | 小時 | 0-23 |
4 | 日期 | 1-31 |
5 | 月份 | 1-12 或 JAN-DEC |
6 | 星期 | 0-6 或 SUN-SAT,其中 0 和 7 都表示周日 |
7 | 年(可選) | 空白表示任意年,或者指定特定年份,如 2022、2023 |
② 間隔執(zhí)行
如果需要在固定的時間間隔內(nèi)周期性地執(zhí)行任務(wù),可以使用 @Scheduled(fixedRate = 時間間隔) 或 @Scheduled(fixedDelay = 時間間隔) 注解來指定時間間隔,如下所示:
@Component
public class MyTask {
@Scheduled(fixedRate = 5000)
public void runTask() {
// 每 5 秒執(zhí)行一次任務(wù)
}
}
③延遲執(zhí)行
如果需要在應(yīng)用啟動后延遲一段時間后執(zhí)行任務(wù),可以使用 @Scheduled(initialDelay = 延遲時間) 注解來指定延遲時間,如下所示:
@Component
public class MyTask {
@Scheduled(initialDelay = 5000, fixedRate = 5000)
public void runTask() {
// 在應(yīng)用啟動后延遲 5 秒執(zhí)行任務(wù),之后每 5 秒執(zhí)行一次任務(wù)
}
}
三、代碼測試
我們就以間隔執(zhí)行進行測試,測試方法每3秒執(zhí)行一次。
1.測試代碼
@Slf4j
@Service
public class FixedDelayTask {
private static int count1 = 1;
@Scheduled(fixedDelay = 3000)
public void fixedDelay() {
log.info(String.format("第%s次執(zhí)行", count1++));
}
}
2.測試結(jié)果
兩次執(zhí)行相隔3秒鐘,并且線程名也是以我們自定義的為前綴。