1. 今天用@Schedule做了一个定时任务,希望凌晨1点执行,代码如下

@Service  
public class ParseJsonService {

@Scheduled(cron = "0 0 1 * * ?")
public void parseMongodbDataToJson() {
}
}

 

第二天来公司了,发现根本没有执行。然后开始查找问题

2. 首先遇到查到的一个解决方案说是spring的版本的问题,我看了下我以前用的定时任务,的确spring用的是4. 于是我将spring的版本换成了4,发现还是不好使

3. 还有版本说要在spring的配置文件中加上注解驱动

<task:annotation-driven />

并且还要加上default-lazy-init="false"属性,说是不让spring懒加载,但是发现还是不行

3. 又查到版本说要在Bean上加上@Lazy(false),让spring对该Bean在启动的时候就加载,但是发现还是不行

终极解决方案(适合我,不一定适合你, 我用的Spring版本是3,不是4)

第一步:在spring的配置文件中加上

<task:annotation-driven />

第二步:在上述Bean上加上

@EnableScheduling

 

@Service  
@EnableScheduling
public class ParseJsonService {
@Scheduled(cron = "0 0 1 * * ?")
public void parseMongodbDataToJson() {

}
}