Java Spring @Scheduled tasks executing twice

前端 未结 23 1673
清歌不尽
清歌不尽 2020-11-29 09:07

I have a simple test method here that is set to run every 5 seconds and it does, but looking at the System.out you can see it appears to be doing something odd.



        
23条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 09:45

    I had the same problem. I was using annotation based configuration as follows:

    @Configuration
    @EnableScheduling
    public class SchedulerConfig {
    
        @Scheduled(fixedDelay = 60 * 1000)
        public void scheduledJob() { 
            // this method gets called twice... 
        }   
    }
    

    I was also extending AbstractAnnotationConfigDispatcherServletInitializer for initializing the same.

    public class SpringWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    
    @Override
    protected Class[] getRootConfigClasses() {
        return new Class[] { MainConfig.class, SchedulerConfig.class };
    }
    
    @Override
    protected Class[] getServletConfigClasses() {
        return new Class[] {SpringWebConfig.class};
    }
    
    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
    
    @Override
    protected Filter[] getServletFilters() {
        final CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
        encodingFilter.setEncoding(CHARACTER_ENCODING);
        encodingFilter.setForceEncoding(true);
        return new Filter[] { encodingFilter };
    }
    

    }

    Removing the SchedulerConfig.class from getRootConfigClasses() method did the trick for me.

    @Override
    protected Class[] getRootConfigClasses() {
        return new Class[] { MainConfig.class };
    }
    

    I hope this helps.

提交回复
热议问题