Java Spring计划作业无法正常工作

时间:2016-08-29 04:38:34

标签: java spring scheduler

我有一个应该运行预定代码的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秒运行一次。

这是app context 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>

2 个答案:

答案 0 :(得分:4)

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

一旦我添加了带有注释的配置类,代码就开始工作了 -

package com.myproject;

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

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

答案 1 :(得分:0)

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

<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

相关问题