@Scheduled设置线程池
时间: 2023-12-09 09:37:25 浏览: 90
可以通过配置线程池来实现@Scheduled注解的定时任务的多线程处理。以下是两种实现方式:
1.在@Configuration类中配置ThreadPoolTaskExecutor:
```java
@Configuration
@EnableScheduling
public class ScheduleConfig {
@Bean
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10); // 设置核心线程数
executor.setMaxPoolSize(20); // 设置最大线程数
executor.setQueueCapacity(200); // 设置队列容量
executor.setKeepAliveSeconds(60); // 设置线程空闲时间
executor.setThreadNamePrefix("taskExecutor-"); // 设置线程名前缀
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 设置拒绝策略
return executor;
}
}
```
2.在@Scheduled注解中指定线程池:
```java
@Component
public class ScheduledTask {
@Autowired
private ThreadPoolTaskExecutor taskExecutor;
@Scheduled(cron = "0/5 * * * * ?")
public void task() {
taskExecutor.execute(() -> {
// 任务逻辑
});
}
}
```
阅读全文