@scheduled是单线程,同一时间有多个定时任务,且数据量比较大则会阻塞其他定时任务。
修改方法:配置线程池——
方法一.使用异步
1.添加全局@EnableAsync 注解,开启对异步的支持
@Component
@EnableScheduling
@EnableAsync
public class ScheduleTask {
}
2.方法中添加@Async,将定时任务设置成异步执行(该异步执行器每次都会开启一个子线程执行,性能消耗比较大,所以最好是自己配置线程池,如第3步创建指定线程池,或者第4步定义全局线程池)
@Scheduled(fixedDelay =60 * 1000)
@Async
public void hello() {
System.out.println("Hello"+new Date());
}
3.可使用@Async(“executor1”) ,配置线程池 public Executor executor1() {},指定使用“executor1”
@Scheduled(fixedDelay =60 * 1000)
@Async("executor1")
public void hello() {
System.out.println("Hello"+new Date());
}
4.可定义全局线程池,实现 AsyncConfigurer 或者继承 AsyncConfigurerSupport
@Configuration
@EnableAsync
public class ThreadPoolTaskExecutorConfig {
@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;
}
}
PS:没有配置线程池时,会默认使SimpleAsyncTaskExecutor。
方法二. 将Scheduled配置成成多线程执行
第一种:通过实现SchedulingConfigurer接口的方式
@Configuration
public class ScheduleThreadPoolConfig implements SchedulingConfigurer {
@Resource
private TaskSchedulerBuilder builder;
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
ThreadPoolTaskScheduler taskScheduler = builder.build();
taskScheduler.initialize();
taskRegistrar.setScheduler(taskScheduler);
}
}
第二种:手动注册 ThreadPoolTaskScheduler 和 ThreadPoolTaskExecutor 进入spring 容器
@Configuration
public class InitThreadPoolTaskScheduler {
@Bean(name = {"ThreadPoolTaskScheduler"})
public ThreadPoolTaskScheduler ThreadPoolTaskScheduler(TaskSchedulerBuilder builder){
ThreadPoolTaskScheduler taskScheduler = builder.build();
// taskScheduler.initialize();
return taskScheduler;
}
@Lazy
@Bean(
name = {"applicationTaskExecutor", "taskExecutor"}
)
public ThreadPoolTaskExecutor applicationTaskExecutor(TaskExecutorBuilder builder) {
return builder.build();
}
}
参考博客:https://blog.csdn.net/bug_chen_xue/article/details/109532155