天天看點

解決多條定時任務同時執行造成系統阻塞的問題

普通的定時任務,會一個一個執行,當同一時間有多個定時任務啟動并且含有資料量比較大的任務時,會阻塞其他的定時任務,這樣會産生一系列的問題;

解決辦法:将定時任務放入線程池。

配置如下:

1、添加全局@EnableAsync 注解,開啟對異步的支援

@EnableAsync //開啟對異步的支援
@Component
public class sopServiceRecoveryController {}
           

2、添加@Async 注解,将該定時任務設定成異步執行

@Async("executor1")
    @Scheduled(cron = "0 0/5 * * * ?")
    public void test01(){
        logger.info("test01---"+new Date());
        return;
    }

    @Async
    @Scheduled(cron = "0 0/5 * * * ?")
    public void test02(){
        logger.info("test02---"+new Date());
        return;
    }

    @Async
    @Scheduled(cron = "0 0/5 * * * ?")
    public void test03(){
        logger.info("test03---"+new Date());
        return;
    }

           

①@Async(“executor1”)注解可配置進入的線程池名稱

②該異步執行器每次都會開啟一個子線程執行,性能消耗比較大,是以最好是自己配置線程池

3、配置線程池

使用@EnableAsync 注解,開啟對異步的支援

@Configuration
@EnableAsync   //開啟對異步的支援
public class ThreadPoolTaskExecutorConfig {

 //配置線程池--線程池01
 @Bean
 public Executor executor1() {
     ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
     executor.setThreadNamePrefix("test-schedule1-");
     executor.setMaxPoolSize(20);
     executor.setCorePoolSize(15);
     executor.setQueueCapacity(0);
     executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
     return executor;
 }

}

           

特别注意:

沒有配置自己的線程池時,會預設使用SimpleAsyncTaskExecutor。