如何快速的設(shè)計(jì)一個定時(shí)任務(wù),讓程序在指定的時(shí)間規(guī)則內(nèi)執(zhí)行,或循環(huán)執(zhí)行切端。schedule是一個非常好的工具彻坛,spring-boot默認(rèn)就支持schedule顷啼。
在使用schedule的時(shí)候,我們會發(fā)現(xiàn)如果一個應(yīng)用下面有多個task使用@Schedule注解是昌屉,如果時(shí)間有沖突的時(shí)候钙蒙,同時(shí)只會執(zhí)行一個task,其他的task會在一個task執(zhí)行完成后间驮,在執(zhí)行下一個task躬厌。schedule不能同時(shí)執(zhí)行多個任務(wù)
造成這個現(xiàn)象的原因是spring-boot的schedule默認(rèn)只有1個線程。不能同時(shí)執(zhí)行多個task。我們只需要修改pool-size就可以了
第一種方法扛施。實(shí)現(xiàn)SchedulingConfigurer接口鸿捧,重寫configureTasks方法,設(shè)置線程池疙渣。@Configuration
@Configuration
public class ScheduleConfig implements SchedulingConfigurer {
? ? @Override
? ? public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
? ? ? ? scheduledTaskRegistrar.setScheduler(Executors.newScheduledThreadPool(5));
? ? }
}
第二種方法(沒試過)匙奴,據(jù)說spring-boot2.1后面,支持在application.properties里面配置配置項(xiàng)妄荔。
spring.task.scheduling.pool.size=20
歡迎訪問個人博客交流>>schedule如何同時(shí)執(zhí)行多個任務(wù)泼菌,schedule不能同時(shí)執(zhí)行多個任務(wù)