繁体   English   中英

Java Spring Scheduled作业不起作用

[英]Java Spring Scheduled job not working

我有一个应该运行预定代码的Web应用程序:

package com.myproject.daemon.jobs;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class MyDaemonJob  {

    private static final Logger log = LoggerFactory.getLogger(MyDaemonJob.class);

    @PostConstruct
    public void init() {
        log.info("MyDaemonJob is intialized " );
    }

    @Scheduled(fixedDelay = 1000)
    public void startDaemon()  {
        try {
            log.info("MyDaemonJob is running ...");
        } catch (Exception e) {
            log.error("Encountered error running scheduled job: " + e.getMessage());
        }
    }
}

正如我从PostConstruct日志中看到的那样,它肯定被识别为Spring bean并已初始化。 但是,带有@Scheduled批注的方法永远不会运行,尽管它应该每1秒运行一次。

这是应用程序上下文xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
                       http://www.springframework.org/schema/beans/spring-beans.xsd
                       http://www.springframework.org/schema/context
                       http://www.springframework.org/schema/context/spring-context-4.0.xsd">

<context:component-scan base-package="
    com.myproject.daemon.jobs,
    com.myproject.product" />

</beans>

谢谢大家的快速帮助。 这真的很有帮助。

一旦我添加了带有注释的config类,代码就开始工作,如下所示-

package com.myproject;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

@Configuration
@EnableScheduling
public class AppConfig {
    // various @Bean definitions
}

要使用@scheduled批注,必须在spring bean配置xml文件中包含spring任务名称空间。 您可以在xml配置文件中更新以下名称空间。

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
                       http://www.springframework.org/schema/beans/spring-beans.xsd
                       http://www.springframework.org/schema/context
                       http://www.springframework.org/schema/context/spring-context-4.0.xsd
                       http://www.springframework.org/schema/task 
                       http://www.springframework.org/schema/task/spring-task-4.1.xsd">

否则,如果您使用spring-boot应用程序,则可以在配置文件中包含@EnableScheduling

暂无
暂无

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

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