先看普通状态下的打印结果。使用定时任务前提 是要 配置好 @EnableScheduling。链接

  1. @Component
  2. public class ScheduleTask {
  3. @Scheduled(cron = "0/5 * * * * *")
  4. public void startAAATasks(){
  5. System.out.println("任务111,开始时间:" + dateFormat.format(new Date()));
  6. try {
  7. Thread.sleep(1000);
  8. }catch (Exception e){
  9. e.printStackTrace();
  10. }
  11. System.out.println("任务111,结束时间:" + dateFormat.format(new Date()));
  12. }
  13. @Scheduled(cron = "0/5 * * * * *")
  14. public void startBBBTasks(){
  15. System.out.println("任务222,开始时间:" + dateFormat.format(new Date()));
  16. try {
  17. Thread.sleep(1000);
  18. }catch (Exception e){
  19. e.printStackTrace();
  20. }
  21. System.out.println("任务222,结束时间:" + dateFormat.format(new Date()));
  22. }

这里有两个任务,这个每5秒执行一次的任务,每个任务 我中间,睡眠1秒。发现打印结果是,两个任务运行时间,是串行下来了,其中一个执行结束,另一个才开始。

image.png

定时任务 并行的方法一

  1. public class PrisonManageApplication {
  2. /**
  3. * 启动程序.
  4. *
  5. * @param args
  6. */
  7. public static void main(String[] args) {
  8. SpringApplication.run(PrisonManageApplication.class, args);
  9. System.out.println("启动成功~~~~~~~~~~");
  10. }
  11. // 启动类加上这串代码
  12. @Bean
  13. public TaskScheduler taskScheduler() {
  14. ThreadPoolTaskScheduler taskExecutor = new ThreadPoolTaskScheduler( ) ;
  15. taskExecutor. setPoolSize(50) ;
  16. return taskExecutor ;
  17. }
  18. }

定时任务 并行的方法二

给类添加注解@EnableAsync,并给方法添加注解@Async。

  1. @Component
  2. @EnableAsync
  3. public class ScheduleTask {
  4. @Async
  5. @Scheduled(cron = "0/5 * * * * *")
  6. public void startAAATasks(){
  7. System.out.println("任务111,开始时间:" + dateFormat.format(new Date()));
  8. try {
  9. Thread.sleep(1000);
  10. }catch (Exception e){
  11. e.printStackTrace();
  12. }
  13. System.out.println("任务111,结束时间:" + dateFormat.format(new Date()));
  14. }
  15. @Async
  16. @Scheduled(cron = "0/5 * * * * *")
  17. public void startBBBTasks(){
  18. System.out.println("任务222,开始时间:" + dateFormat.format(new Date()));
  19. try {
  20. Thread.sleep(1000);
  21. }catch (Exception e){
  22. e.printStackTrace();
  23. }
  24. System.out.println("任务222,结束时间:" + dateFormat.format(new Date()));
  25. }
  26. }

两个方法结果都一样,可以看到两个任务的启动时间是同时的
image.png