如何解决spring定时器被执行两次的问题

因为最近用到定时任务的功能,因此用到了spring的定时任务,配置方式如下

1.新建一个spring-scedul.xml文件

里面配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/task
   http://www.springframework.org/schema/task/spring-task-4.1.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context.xsd">


  <!--配置任务扫描-->
 <task:annotation-driven />
  <context:component-scan base-package="com.hfs.modules.schedul"></context:component-scan>
  <!-- 扫描任务 -->
</beans>

2.在springMVC.xml中引入spring-scedul.xml

<import resource="classpath:spring-scedul.xml"/>(应该由web.xml去加载)

3、创建任务类

@Component
public class weatherTask {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Scheduled(cron = "0/5 * * * * ? ") //  每隔5秒执行
    public void taskCycle() {

        logger.info("------每隔5秒执行---------");    
    }

结果:项目启动时每次执行定时任务都会执行两次。

然后百度一大堆感觉不靠谱。。。

可能是因为项目启动时配置文件被加载了两次,将上面的2步骤改为在web.xml中配置加载spring-scedul.xml文件,如下:

<!-- 加载Spring配置文件 -->
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:/spring-context.xml,classpath:spring-schedul.xml</param-value>
</context-param>

结果发现启动时报错:Configuration problem: Only one AsyncAnnotationBeanPostProcessor may exist within the context

意思是有重复加载的bean

解决方案:将spring-scedul.xml中的 <task:annotation-driven />给干掉,问题就解决了,定时任务不会被加载两次了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值