春季3预定任务运行3次

mik*_*e27 9 spring scheduled-tasks

我有一个非常简单的方法,计划每10秒运行一次,如下所示:

@Component
public class SimpleTask {

    @Scheduled(fixedRate=10000)
    public void first() {
        System.out.println("Simple Task  " + new Date());
    }
}
Run Code Online (Sandbox Code Playgroud)

配置:

<task:annotation-driven executor="myExecutor" scheduler="myScheduler" />
<task:executor id="myExecutor" pool-size="5"  /> 
<task:scheduler id="myScheduler" pool-size="10"  />
Run Code Online (Sandbox Code Playgroud)

我的问题是我的方法每10秒被调用3次.它应该只被调用一次.我究竟做错了什么?我使用Spring Source ToolSuite和SpringSource tc Server 6.

jon*_*mps 22

我有同样的问题.其中一个原因是Spring 3.0.0中的一个错误.我升级到3.0.5,重复次数降到了两次.

另一个原因是因为我的具有@Scheduled方法的类被实例化了两次.发生这种情况是因为上下文配置被加载了两次.在web.xml中,我将ContextLoaderListener和DispatcherServlet指向相同的上下文配置文件:

...
<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
...
Run Code Online (Sandbox Code Playgroud)

WEB-INF/applicationContext.xml是ContextLoaderListener的默认上下文配置.因此,请确保ContextLoaderListener和ServletDispatcher使用不同的上下文文件.我最终创建了一个没有任何bean定义的/WEB-INF/spring-servlet.xml,它运行得很完美.