Java Scheduled定时任务(二)——开启多线程定时任务

ゝ一纸荒年。 2024-04-06 14:58 148阅读 0赞

我们在Java Scheduled定时任务中已经学到了如何开启定时任务,但却在同时开启多个定时任务的时候,遇到了新的问题,Scheduled定时任务是单线程的,无法满足同一个时间开启多个定时任务,因此,我们进行了如下调整:

1、新建一个配置类;

  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.scheduling.annotation.EnableAsync;
  4. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
  5. import java.util.concurrent.Executor;
  6. @Configuration
  7. @EnableAsync
  8. public class AsyncConfig {
  9. private int corePoolSize = 10;
  10. private int maxPoolSize = 200;
  11. private int queueCapacity = 10;
  12. @Bean
  13. public Executor taskExecutor() {
  14. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  15. executor.setCorePoolSize(corePoolSize);
  16. executor.setMaxPoolSize(maxPoolSize);
  17. executor.setQueueCapacity(queueCapacity);
  18. executor.initialize();
  19. return executor;
  20. }
  21. }

2、在定时任务中添加@Async异步注解,即可开启多线程定时任务。

但通过如上方法,又会出现新的问题,如果某个定时任务在规格的时间内没有运行完,而它新的定时任务再次开启,就会出现两个定时任务同时对表的数据进行操作,会导致数据各种的错误,因此,再次对定时任务进行处理,增加锁机制(synchronized),对未执行完的定时任务及时锁住,不让它开启下一个定时任务。

实例如下所示:

  1. private static Object lkm1 = new Object();
  2. private static Object lkm2 = new Object();
  3. /**
  4. *
  5. * @description:
  6. * @author: lkm
  7. * @date: 2023/9/7 9:15
  8. **/
  9. @Scheduled(cron = "0 0/1 * * * ?")
  10. public void scheduledTask1() throws Exception {
  11. synchronized(lkm1){
  12. Date date =new Date();
  13. System.out.println("====================任务开始1=================");
  14. System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
  15. Thread.sleep(120000);//2分钟
  16. System.out.println("====================任务1,结束=================");
  17. }
  18. }
  19. /**
  20. *
  21. * @description:
  22. * @author: lkm
  23. * @date: 2023/9/7 9:15
  24. **/
  25. @Scheduled(cron = "0 0/1 * * * ?")
  26. public void scheduledTask2() throws Exception {
  27. synchronized(lkm2){
  28. Date date =new Date();
  29. System.out.println("====================任务开始2=================");
  30. System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
  31. Thread.sleep(120000);//2分钟
  32. System.out.println("====================任务2,结束=================");
  33. }
  34. }

发表评论

表情:
评论列表 (有 0 条评论,148人围观)

还没有评论,来说两句吧...

相关阅读