@Scheduled不执行的原因

时间:2023-03-09 17:29:06
@Scheduled不执行的原因

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

  1. @Service
  2. public class ParseJsonService {
  3. @Scheduled(cron = "0 0 1 * * ?")
  4. public void parseMongodbDataToJson() {
  5. }
  6. }

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

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

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

  1. <task:annotation-driven />

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

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

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

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

  1. <task:annotation-driven />

第二步:在上述Bean上加上

  1. @EnableScheduling

代码如下:

    1. @Service
    2. @EnableScheduling
    3. public class ParseJsonService {
    4. @Scheduled(cron = "0 0 1 * * ?")
    5. public void parseMongodbDataToJson() {
    6. }
    7. }

http://blog.****.net/u011734144/article/details/52849868