-
pom.xml 引入 springboot 相关依赖
-
入口类加 @EnableScheduling注解(有些版本不加该注解也会执行定时任务。请注意:有些版本即使注释掉该注解,也会执行定时任务)
@SpringBootApplication
@EnableScheduling
public class XXXApplication {
}
- 建立AsyncTaskConfig类(配置多线程异步任务)
@Configuration
@EnableAsync
public class AsyncTaskConfig {
@Bean
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setKeepAliveSeconds(1800);
executor.setMaxPoolSize(1000);
executor.setQueueCapacity(500);
executor.initialize();
return executor;
}
}
- 建立具体的任务类
@Component
public class MyTask {
// @Async 表示使用异步
// @Scheduled:initialDelay:启动时延迟 1 秒执行,fixedRate:3秒执行一