SpringBoot中集成的简单的定时任务----Scheduled
//在启动入口中添加@EnableScheduling
@SpringBootApplication
@EnableScheduling
public class JobApplication {
public static void main(String[] args) {
SpringApplication.run(JobApplication.class, args);
}
}
//组件注入,交给spring管理 或者此处可以直接使用@EnableScheduling
@Component
public class TestJob {
@Scheduled(cron="0 0/1 * * * ?")
public void test() {
System.out.println("定时任务开始执行");
}
}
很简单就可以创建一个定时任务了,但是此时存在一个问题,一旦存在多个类(或者多个任务),多个类之间是顺序执行。
多任务需要同时执行,需要为定时任务设置线程池
@Configuration
public class TestScheduleConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
//线程数>=任务数
scheduledTaskRegistrar.setScheduler(Executors.newScheduledThreadPool(2));
}
}