@Scheduled Spring定时任务每次执行两次解决方案

时间:2022-01-30 21:50:41

      在执行定时任务的时候我遇到了一种情况,一个定时器每次会被执行两次,这就让人有点困惑,猜测肯定是哪里配置出了问题(配了两个当前上下文情况),看了一下网上很多解释,没有找到与自己相匹配的情况,所以自己也不断尝试修改配置文件。终于找到错误原因,这里把错误代码和原因贴出来方便与我有相同困惑的朋友参考。

     首先错误的日志输出如下图:

      @Scheduled Spring定时任务每次执行两次解决方案

      在我们的web.xml文件中,我们有对spring整合配置,比如配置监听器,上下文加载对象,拦截器,会话的管理等等。

    

   <!--
        The Bootstrap listener to start up and shut down Spring's root
        WebApplicationContext. It is registered to Servlet Container
    -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>


    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
    </context-param>

    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>

    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

      上面是我对监听器Listener和上下文对象contextConfigLocation和DispatcherServlet的配置, 出错原因就是没有设置contextConfigLocation为空,导致加载了两次配置文件,所以就有两个操作的上下文的session出现。把上面的代码添加一段即可:

<!--
        The Bootstrap listener to start up and shut down Spring's root
        WebApplicationContext. It is registered to Servlet Container
    -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>


    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
    </context-param>

    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--加上了这个 定时器就不会同时执行两次了-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value></param-value>
        </init-param>

        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>

    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


     重新运行程序,log日志输出结果:

@Scheduled Spring定时任务每次执行两次解决方案