首先,需要了解@Scheduled 和@Async这俩注解的区别
- @Scheduled 任务调度注解,主要用于配置定时任务;springboot默认的调度器线程池大小为 1。
注意:在spring中的@schedule默认的线程池中只有一个线程,所以如果在多个方法上加上@schedule的话,此时就会有多个任务加入到延时队列中,因为只有一个线程,所以任务只能被一个一个的执行
- @Async 任务异步执行注解,主要用于方法上,表示当前方法会使用新线程异步执行;springboot默认执行器线程池大小为100。
此注解会将这个任务放入到一个异步线程中执行,不会阻塞主线程,可以用在一些比较耗时并且不用考虑返回值的一些操作中
如何使用
- 开启异步任务的开关 在启动类上添加注解@EnableAsync @EnableScheduling
@EnableAsync
@EnableScheduling
@SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
2.在定时任务上加上注解
@Async
@Scheduled(fixedDelay = 1000)
public void executeUpdateYqTask() {
System.out.println(Thread.currentThread().getName() + " >>> task one " + format.format(new Date()));
}
@Async
@Scheduled(fixedDelay = 1000)
public void executeRepaymentTask() throws InterruptedException {
System.out.println(Thread.currentThread().getName() + " >>> task two " + format.format(new Date()));
Thread.sleep(5000);
}
可以看到控制台输出已经是异步执行了
总结
- 默认@schedule 线程池默认只有一个线程,多个任务时串行 串行
- 默认@schedule + @Aysnc 多个任务之间串行,单个任务非阻塞异步执行 并行+异步