Spring @Scheduled task runs twice

2020-02-06 10:15发布

I am creating an @Scheduled task to run every 5 seconds. As has been a problem in other questions, my task is running twice!

I have looked at other questions, and read the applicable documentation here, but I have not been able to figure out the problem.

I know that two seperate instances of my @Scheduled class are getting instantiated when I start my tomcat server. I have also figured out when they are instantiated in reference to my log file.

One associated with this log line :

INFO: Initializing Spring root WebApplicationContext

and another with this log line:

INFO: Initializing Spring FrameworkServlet 'servlet'

Here is the spring config file.

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
   xmlns:security="http://www.springframework.org/schema/security"
   xmlns:task="http://www.springframework.org/schema/task"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">

<context:component-scan base-package="web.controllers"/>
<context:component-scan base-package="services"/>
<context:component-scan base-package="dao"/>
<context:component-scan base-package="scheduled"/>
<context:property-placeholder location="/WEB-INF/application.properties"/>

<mvc:annotation-driven/>
<mvc:default-servlet-handler/>

<task:annotation-driven />

And my simple java class:

package scheduled;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class Notifier {

@Scheduled(fixedDelay = 5000)
public void notifyUsersOfBidItems() {
    try {
        System.out.println(this);

    } catch (Exception e) {
        e.printStackTrace();
    }

}
}

Also, I am using Spring 4.

EDIT: Adding web.xml

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
     version="3.0">
<display-name>Archetype Created Web Application</display-name>

<servlet>
    <servlet-name>servlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring_config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

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

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

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring_config.xml</param-value>
</context-param>

<error-page>
    <error-code>404</error-code>
    <location>/error/notFound</location>
</error-page>

<error-page>
    <error-code>403</error-code>
    <location>/error/notFound</location>
</error-page>


<error-page>
    <location>/error/internal</location>
</error-page>

<!-- Spring Security -->
<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

3条回答
狗以群分
2楼-- · 2020-02-06 10:45

I believe this is caused by same config file being loaded twice in your web.xml

<servlet>
    <servlet-name>servlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring_config.xml</param-value> <!-- FIRST -->
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring_config.xml</param-value> <!-- SECOND -->
</context-param>

EDIT To fix it:

Create another file servlet-servlet.xml (this will be picked up by the ServletDispatcher config by default since it matches the file by servlet name) The file will contain this:

<beans>
    <context:component-scan base-package="web.controllers"/>
    <mvc:annotation-driven/>
    <mvc:default-servlet-handler/>
</beans>

Modify the original file (spring-config.xml):

<beans>
    <task:annotation-driven />
    <context:component-scan base-package="services"/>
    <context:component-scan base-package="dao"/>
    <context:component-scan base-package="scheduled"/>
    <context:property-placeholder location="/WEB-INF/application.properties"/>
</beans>

Modify your web xml servlet config to following:

<servlet>
    <servlet-name>servlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
查看更多
看我几分像从前
3楼-- · 2020-02-06 10:52

I also had this problem. I am using Spring 4. I have no xml configuration. Everything is configured with annotations and Java config.

I have a base configuration and a WebConfiguration. the error was caused by using @ComponentScan in both configurations. I removed component scan from base configuration.

@EnableWebMvc
@ComponentScan(basePackages = { "com.myservice" })
@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter {
  @Bean
  public UrlBasedViewResolver setupViewResolver() {
    UrlBasedViewResolver resolver = new UrlBasedViewResolver();
    resolver.setPrefix("/WEB-INF/jsp/");
    resolver.setSuffix(".jsp");
    resolver.setViewClass(JstlView.class);
    return resolver;
  }

  @Override
  public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
  }
}

@Configuration
@EnableScheduling
//@ComponentScan(basePackages = { "com.myservice" })  
@PropertySource("${myservice.properties.location:classpath:myservice.properties}")
public class BaseConfiguration  {


  @Autowired
  Environment environment;

  @Bean
  public static PropertySourcesPlaceholderConfigurer properties() {
    return new PropertySourcesPlaceholderConfigurer();
  }
查看更多
爷、活的狠高调
4楼-- · 2020-02-06 11:04

solution : Quartz + Spring double execution java config

getServletConfigClasses()-> return null;

    public static class MvcWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {


    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{WebConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};

    }
}

example code solution

查看更多
登录 后发表回答