Spring @Scheduled任务运行两次
我正在创建一个@Scheduled
任务,每5秒运行一次。 由于其他问题一直存在问题,我的任务是运行两次!
我已经查看了其他问题,并在此阅读了适用的文档,但我无法弄清楚问题所在。
我知道当我启动tomcat服务器时,我的@Scheduled
类的两个单独实例正在实例化。 我还想到了它们在引用我的日志文件时被实例化的时候。
与此日志行相关联的一个:
信息:初始化Spring根WebApplicationContext
另一个有这个日志行:
信息:初始化Spring FrameworkServlet’servlet’
这是spring配置文件。
而我的简单java类:
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(); } } }
另外,我使用的是Spring 4。
编辑: Adding web.xml
Archetype Created Web Application servlet org.springframework.web.servlet.DispatcherServlet contextConfigLocation /WEB-INF/spring_config.xml 1 servlet / org.springframework.web.context.ContextLoaderListener contextConfigLocation /WEB-INF/spring_config.xml 404 /error/notFound 403 /error/notFound /error/internal springSecurityFilterChain org.springframework.web.filter.DelegatingFilterProxy springSecurityFilterChain /*
我相信这是由在web.xml中加载两次的相同配置文件引起的
servlet org.springframework.web.servlet.DispatcherServlet contextConfigLocation /WEB-INF/spring_config.xml 1 contextConfigLocation /WEB-INF/spring_config.xml
编辑修复它:
创建另一个文件servlet-servlet.xml(默认情况下,这将由ServletDispatcher配置获取,因为它通过servlet名称与文件匹配)该文件将包含以下内容:
修改原始文件(spring-config.xml):
将您的web xml servlet配置修改为以下内容:
servlet org.springframework.web.servlet.DispatcherServlet 1
我也有这个问题。 我使用的是Spring 4.我没有xml配置。 一切都配置了注释和Java配置。
我有一个基本配置和一个WebConfiguration。 错误是由两个配置中的@ComponentScan引起的。 我从基本配置中删除了组件扫描。
@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(); }
解决方案:Quartz + Spring双执行java配置
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[]{"/"}; } }
示例代码解决方案