SpringBoot 配置定时任务多线程异步执行

SpringBoot使用==@scheduled==执行定时任务是是单线程执行的,如果某个任务阻塞或者执行时间过长,会影响其他定时任务的执行。一般在项目内都需要进行相应的配置来允许定时任务并行执行

最佳方案:

  1. 手动创建线程池,指定线程数大小
@EnableAsync
@Configuration
public class ScheduleConfig {
   
    //如果定时任务上不加@Async时会使用这个线程池执行
    @Bean
    public TaskScheduler taskExecutor() {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(50);
        taskScheduler.setThreadNamePrefix("task-scheduler");
        return taskScheduler;
    }
    
    //加了@Async时会使用这个线程池执行
    @Primary
    @Bean
    public ThreadPoolTaskExecutor springTaskExecutor() {
        ThreadPoolTaskExecutor threadPoolExecutor = new ThreadPoolTaskExecutor();
        threadPoolExecutor.setCorePoolSize(16);
        threadPoolExecutor.setMaxPoolSize(32);
        threadPoolExecutor.setThreadNamePrefix("thread-pool");

        return threadPoolExecutor;
    }

}
  1. 定时任务上加@async注解异步执行
@Scheduled(cron = "0/1 * * * * ? ")
public void test(){
    log.info("任务启动成功-->"+ DateUtil.now());
}

你可能感兴趣的:(springBoot,spring,boot,java,后端)