spring Scheduled定时任务配置原本感觉很简单,但是配置之后发现不生效,折腾了一小会才找到原因,将具体过程记录如下;
1修改spring-context.xml 在配置文件开头声明task
<?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" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.0.xsd"
default-lazy-init="true">
<description>Spring公共配置 </description>
<!-- 注意:此处 com.ruisitech.bi.service是你的定时任务实体类所在的包,需要修改成自己的-->
<context:component-scan base-package="com.ruisitech.bi.service">
</context:component-scan>
<!-- 配置定时器开关 里面可以配置很多参数,这里只是简单的打开task,并支持@Scheduled -->
<!-- 配置定时器注解开关 里面可以配置很多参数,这里只是简单的打开task,并支持@Scheduled -->
<task:scheduler id="Scheduler" pool-size="10"/>
<task:annotation-driven scheduler="Scheduler" proxy-target-class="true"/>
</beans>
2java代码如下
@Service
@Component
public class CheckHiveDataToCK {
@Autowired
private RhService rhService;
@Scheduled(cron="0 7 * * * ?")
public void checkDau(){
System.out.println("task------");
}
}
但是启动web项目后,发现上面的代码的定时任务并没有执行,奇了怪了,查阅了资料后发现是上面一处不起眼的配置导致的,
default-lazy-init="true" ,此处配置为懒加载,所以如所有的bean都是懒加载的,导致定时任务所在的bean根本没有实例化,里面的定时任务也没有执行。修改为:
default-lazy-init="false"即可。