博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring Boot @Scheduled 执行两遍
阅读量:7135 次
发布时间:2019-06-28

本文共 1749 字,大约阅读时间需要 5 分钟。

hot3.png

使用spring cloud[Dalston.SR1]版本开发定时job时,发现job执行了两次;

下面日志里发现一个job被一个任务调度池(task-scheduler)里的两个worker(task-scheduler-1 和 task-scheduler-2)执行,很奇怪;

2018-02-23 14:28:30.001 [task-scheduler-2] INFO  c.k.micro.cfca.scheduled.ContractSealApplyJob - ==回调job==开始==2018-02-23 14:28:30.002 [task-scheduler-2] INFO  c.k.micro.cfca.scheduled.ContractSealApplyJob - ==回调job==结束==2018-02-23 14:28:30.003 [task-scheduler-1] INFO  c.k.micro.cfca.scheduled.ContractSealApplyJob - ==回调job==开始==2018-02-23 14:28:30.003 [task-scheduler-1] INFO  c.k.micro.cfca.scheduled.ContractSealApplyJob - ==回调job==结束==

在构造方法里加入log,确认了类只被加载了一次;

示例代码:

@RefreshScope@Component@EnableSchedulingpublic class ContractSealApplyJob{	@Value("${value1}")	private String value1;	/**     * 进行回调job     */    @Scheduled(cron = "${0/30 * * * * *}")//每30秒    public void doCallBack(){		logger.info("==回调job==开始==");		....		logger.info("==回调job==结束==");	}}

发现是spring cloud config 里的注解@RefreshScope导致;正确用法是把配置项放到一个Config类里面;然后在Job里注入。 @RefreshScope注解的类,在运行时刷新后,会重新生成一个新的实例;不过在上述Job里并未被重新实例化(没有刷新),而是把Job放入池里两次。

/** * Convenience annotation to put a @Bean definition in * {@link org.springframework.cloud.context.scope.refresh.RefreshScope refresh scope}. * Beans annotated this way can be refreshed at runtime and any components that are using * them will get a new instance on the next method call, fully initialized and injected * with all dependencies. *  * @author Dave Syer * */@Target({ ElementType.TYPE, ElementType.METHOD })@Retention(RetentionPolicy.RUNTIME)@Scope("refresh")@Documentedpublic @interface RefreshScope {	/**	 * @see Scope#proxyMode()	 */	ScopedProxyMode proxyMode() default ScopedProxyMode.TARGET_CLASS;}

 

@RefreshScope还有别的坑,详见:

转载于:https://my.oschina.net/placeholder/blog/1623070

你可能感兴趣的文章
CentOS VMware 配置IP小结 静态 配置 桥接 NAT
查看>>
Storm概念学习系列之storm核心组件
查看>>
slf4j,log4j,logback 初步使用
查看>>
对称矩阵、Hermite矩阵、正交矩阵、酉矩阵、奇异矩阵、正规矩阵、幂等矩阵
查看>>
(转) Deep Learning Research Review Week 2: Reinforcement Learning
查看>>
Java学习之强引用,弱引用,软引用 与 JVM
查看>>
配置163Yum源自动判断你的系统是Centos版本(适用于5.x或6.x)
查看>>
js(javascript) 继承的5种实现方式
查看>>
【分布式】Zookeeper系统模型
查看>>
tomcat并发
查看>>
Nginx配置Https
查看>>
【UE4游戏开发】安装UE4时报SU-PQR1603错误的解决方法
查看>>
Microsoft.CodeAnalysis 入门
查看>>
replace和replaceAll的区别
查看>>
前端学PHP之PHP操作memcache
查看>>
J2EE项目修改编码问题
查看>>
mybatis.net insert 返回主键
查看>>
10 个最佳的网站分析方法
查看>>
MVC3的安装方法(含安装包)
查看>>
hdoj:2076
查看>>