springboot schedule 解決定時任務不執(zhí)行的問題
@schedule 注解 是springboot 常用的定時任務注解,使用起來簡單方便,但是如果定時任務非常多,或者有的任務很耗時,會影響到其他定時任務的執(zhí)行,因為schedule 默認是單線程的,一個任務在執(zhí)行時,其他任務是不能執(zhí)行的.解決辦法是重新配置schedule,改為多線程執(zhí)行.只需要增加下面的配置類就可以了.
import org.springframework.boot.autoconfigure.batch.BatchProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import java.lang.reflect.Method;
import java.util.concurrent.Executors;
@Configuration
public class ScheduleConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
Method[] methods = BatchProperties.Job.class.getMethods();
int defaultPoolSize = 3;
int corePoolSize = 0;
if (methods != null && methods.length > 0) {
for (Method method : methods) {
Scheduled annotation = method.getAnnotation(Scheduled.class);
if (annotation != null) {
corePoolSize++;
}
}
if (defaultPoolSize > corePoolSize)
corePoolSize = defaultPoolSize;
}
taskRegistrar.setScheduler(Executors.newScheduledThreadPool(corePoolSize));
}
}
源碼 https://github.com/Yanyf765/demo_schedule
總結
以上所述是小編給大家介紹的springboot schedule 解決定時任務不執(zhí)行的問題,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!
- SpringBoot整合canal實現(xiàn)數(shù)據(jù)同步的示例代碼
- 關于SpringBoot整合Canal數(shù)據(jù)同步的問題
- SpringBoot定時任務兩種(Spring Schedule 與 Quartz 整合 )實現(xiàn)方法
- 詳解SpringBoot 創(chuàng)建定時任務(配合數(shù)據(jù)庫動態(tài)執(zhí)行)
- SpringBoot實現(xiàn)動態(tài)定時任務
- Springboot整個Quartz實現(xiàn)動態(tài)定時任務的示例代碼
- SpringBoot 定時任務遇到的坑
- springboot集成schedule實現(xiàn)定時任務
- springboot整合Quartz實現(xiàn)動態(tài)配置定時任務的方法
- SpringBoot定時任務實現(xiàn)數(shù)據(jù)同步的方法
相關文章
大廠禁止SpringBoot在項目使用Tomcat容器原理解析
這篇文章主要為大家介紹了大廠禁止SpringBoot在項目使用Tomcat原理解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-07-07
java 高并發(fā)中volatile的實現(xiàn)原理
這篇文章主要介紹了java 高并發(fā)中volatile的實現(xiàn)原理的相關資料,在多線程并發(fā)編程中synchronized和Volatile都扮演著重要的角色,Volatile是輕量級的synchronized,它在多處理器開發(fā)中保證了共享變量的“可見性”,需要的朋友可以參考下2017-03-03
Spring Cache整合Redis實現(xiàn)方法詳解
這篇文章主要介紹了Spring Cache整合Redis實現(xiàn)方法詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-08-08
MyBatis-Plus多表聯(lián)合查詢并且分頁(3表聯(lián)合)
這篇文章主要介紹了MyBatis-Plus多表聯(lián)合查詢并且分頁(3表聯(lián)合),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-08-08

