spring timer不启动问题

spring写一个timer之后,不启动问题分析。

源文件:
1. timer类文件
@Component("task")
@Lazy
public class Task {
    public Task(){
        System.out.println("construct Task!!!");
    }
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Scheduled(cron = "* * * * * ?")
    public void pushQuestionnaire() {

        System.out.println("定时任务1,自动执行:" + format.format(new Date()));
    }
}

2. spring-config.xml主要配置
    <context:annotation-config />
    <context:component-scan base-package="heller"/>
    <!--开启配置-->
    <task:scheduler id="qbScheduler" pool-size="10"/>
    <task:annotation-driven scheduler="qbScheduler" mode="proxy"/>

3. 启动spring
public class Start {
    public static void main(String[] args) throws InterruptedException {
        ApplicationContext context = new ClassPathXmlApplicationContext("./spring-config.xml");       
    }
}

问题
启动Start类后,不能执行Task里面定义的任务

分析
1. 我们看spring-config.xml里面的配置
<task:scheduler id="qbScheduler" pool-size="10"/>表示创建了一个计划任务的线程池实例。
<task:annotation-driven scheduler="qbScheduler" mode="proxy"/>这个注解表示从spring管理的实例中扫描,看是否有实例带有@Scheduled标签的类,如果有则把这个实例放入任务线程池中。而我们的Task类上的注解Lazy默认为true,也就是不会创建实例,所以也就不会加到任务线程池中。

解决办法
在Task类上面加入@Lazy(false)注解

猜你喜欢

转载自mfkujjisk.iteye.com/blog/2340965