当前位置:首页 > 通信资讯 > 正文

springboot @scheduled(springboot schedule)

目录
  • SpringBoot @Scheduled的并发
  • spring @Scheduled 并发执行

SpringBoot @Scheduled的并发

由于SpringBoot自带的@Scheduled是一个阻塞执行的定时任务,所以效率会很慢,就会造成同一个时间段内只有一个定时任务在执行,其余的就会阻塞

现有两个定时任务

?
1 2 3 4 5 6 7 8 9 10 11 12 13 @Component("aa") public class aa { @Scheduled(cron = "0 44 17 * * ?") public void bb() { try { System.out.println("aa执行时间:" + new Date()); Thread.sleep(65000); System.out.println("aa完成时间:" + new Date()); } catch (Exception e) { e.printStackTrace(); } } }
?
1 2 3 4 5 6 7 8 9 10 11 12 @Component("bb") public class bb { @Scheduled(cron = "0 55 17 * * ?") public void aa() { try { System.out.println("bb执行时间:" + new Date()); Thread.sleep(10000); System.out.println("bb完成时间:" + new Date()); } catch (Exception e) { e.printStackTrace(); } }

默认的在启动项加入@EnableScheduling注解就可以运行了

springboot @scheduled(springboot schedule)

最终,执行的结果令人大跌眼镜。

springboot @scheduled(springboot schedule)

aa的任务由于执行时间需要65秒,超过了bb任务执行的时间,结果bb任务执行的时间被阻塞掉,延迟了5秒执行。

解决方法是在启动项类中加入如下配置即可

?
1 2 3 4 5 6 @Bean public TaskScheduler taskScheduler() { ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); taskScheduler.setPoolSize(50); return taskScheduler; }

如果是xml

?
1 2 3 4 <!-- 注解式 --> <task:annotation-driven executor="myExecutor" scheduler="myScheduler"/> <task:executor id="myExecutor" pool-size="5"/> <task:scheduler id="myScheduler" pool-size="10"/>

spring @Scheduled 并发执行

spring @Scheduled ,默认基于单线程执行,如果需要基于多线程执行,需要在配置文件中配置如下

?
1 2 queue-capacity="500" rejection-policy="CALLER_RUNS" /> scheduler="scheduler" />

具体可以参考spring 帮助文档对annotation-driven的executor和scheduler的解释

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/weixin_43958556/article/details/116456909

如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。