简体   繁体   English

Spring 4 @Scheduled Task执行任务两次

[英]Spring 4 @Scheduled Task is executing task twice

I'm trying to execute some task every X second but the task runs twise. 我正在尝试每隔X秒执行一些任务,但是该任务按时运行。 I'm Using Spring 4.2.5 - the latest version.(I tryed it with 4.05 the same result) 我使用的是Spring 4.2.5-最新版本(我在4.05中尝试了相同的结果)

@Service
@Transactional
@EnableScheduling
public class PaymentServices {


@Autowired
private MMTransactionDAO mmTransactionDAO;



@Scheduled(fixedDelay=230000)
public void getListOfPenddingTransactions() throws MambuApiException {
    System.out.println("JOB Started");
    List<MMPayTransaction> listOfPenddingTransaction = mmTransactionDAO.getListOfPenddingTransaction();

    for(MMPayTransaction transaction : listOfPenddingTransaction){
        if (transaction.getErrorcode().equals("-6")){
            cancelTransactionInMambu(transaction.getMambuClientID(),transaction.getPaymentAmount(),transaction.getFeeAmount());
            transaction.setFinalStatus(TansactionStatus.FAILED);
        }else if(transaction.getErrorcode().equals("-21")){
            cancelTransactionInMambu(transaction.getMambuClientID(),transaction.getPaymentAmount(),transaction.getFeeAmount());
            transaction.setFinalStatus(TansactionStatus.FAILED);
        }else if(transaction.getErrorcode().equals("-18")){
            cancelTransactionInMambu(transaction.getMambuClientID(),transaction.getPaymentAmount(),transaction.getFeeAmount());
            transaction.setFinalStatus(TansactionStatus.FAILED);
        }else if (transaction.getErrorcode().equals("-37")){
            cancelTransactionInMambu(transaction.getMambuClientID(),transaction.getPaymentAmount(),transaction.getFeeAmount());
            transaction.setFinalStatus(TansactionStatus.FAILED);
        }
        else{
            check(transaction.getOperationID());
        }

    }
}

}

here is my web.xml 这是我的web.xml

<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<display-name>Spring MVC Application</display-name>

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

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

<filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>


<filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

UPDATED 更新

here is my application configuration calss: 这是我的应用程序配置清单:

@EnableWebMvc
@Configuration
@ComponentScan({"ge.kapi.*"})
@EnableTransactionManagement
public class AppConfig extends WebMvcConfigurerAdapter {

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory()
{
    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();

    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    vendorAdapter.setGenerateDdl(Boolean.TRUE);
    vendorAdapter.setShowSql(Boolean.TRUE);

    factory.setDataSource(dataSource());
    factory.setJpaVendorAdapter(vendorAdapter);
    factory.setPackagesToScan("ge.kapi");

    Properties jpaProperties = getHibernateProperties();
    factory.setJpaProperties(jpaProperties);

    factory.afterPropertiesSet();
    factory.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
    return factory;
}

private Properties getHibernateProperties() {
    Properties prop = new Properties();
    prop.put("hibernate.show_sql", "true");
    prop.put("hibernate.dialect","ge.kapi.config.SQLServerUnicodeDialect");
    return prop;
}


@Bean(name = "dataSource")
public BasicDataSource dataSource() {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    ds.setUrl("jdbc:sqlserver://host;useUnicode=true;characterEncoding=UTF-8;DatabaseName=Base");
    ds.setUsername("user");
    ds.setPassword("pass");
    return ds;
}




@Bean
public StringHttpMessageConverter stringHttpMessageConverter() {
    return new StringHttpMessageConverter(Charset.forName("UTF-8"));
}

@Bean
public PlatformTransactionManager transactionManager()
{
    EntityManagerFactory factory = entityManagerFactory().getObject();
    return new JpaTransactionManager(factory);
}



@Bean
public InternalResourceViewResolver viewResolver() {
    InternalResourceViewResolver viewResolver
            = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setContentType("text/html; charset=UTF-8");
    viewResolver.setPrefix("/WEB-INF/views/");
    viewResolver.setSuffix(".jsp");
    return viewResolver;
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}

} }

Why is it running TWICE each time? 为什么每次都运行两次TWICE?

Thanks in advance 提前致谢

-- Found Solution -- -找到解决方案-

I have removed @ComponentScan({"ge.kapi.*"}) from AppConfig.java because this scan was also initiated from mvc-dispatcher-servlet.xml like this: 我已从AppConfig.java中删除@ComponentScan({“ ge.kapi。*”}),因为此扫描也是从mvc-dispatcher-servlet.xml启动的,如下所示:

 <context:component-scan base-package="ge.kapi"/>

Now Job starts only ones. 现在,约伯只开始一个。

Thank you all for your time helping me!!! 谢谢大家为我提供的时间!!!

I suggest you check if the bean is being created twice. 我建议您检查是否两次创建了该bean。 It can happen if you have 2 app contexts (root and dispatcher). 如果您有2个应用程序上下文(root和dispatcher),则可能会发生这种情况。

Check if you have declared bean in xml and by annotation too. 检查是否已在xml中声明bean并通过注释声明。

And if you have spring security configuration in your application then keep mvc-dispatcher.xml declaration in of DispatcherServlet and spring-security.xml in of context loader listener . 而且,如果您的应用程序中具有spring安全配置,则将DispatcherServlet中的mvc-dispatcher.xml声明保留在上下文加载器侦听器中,并将spring-security.xml保留在上下文加载器侦听器中。

Otherwise if you keep both xml with DispatcherServlet in that case two object will be created and that is why your scheduler will get call twice. 否则,如果在这种情况下将两个xml与DispatcherServlet一起保留,则将创建两个对象,这就是为什么调度程序将被调用两次的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM