spring定时器用Annotation实现
由于项目中需要定时更新一些数据,所以用到了spring的定时器,在使用Quartz过程中,遇到了一些麻烦,最终牵扯的错误太多:
1、我的一个Service类中需要加入定时执行即Service extends QuartzJobBean,但是Service类中使用@Autowired注入了属性:dao对象
2、在executeInternal方法执行过程中,dao对象一直为null。
3、尝试了各种办法,最终在配置文件中这样配置(这种配置网上多的是)
使用jobDataAsMap这个属性
<bean id="quartzClock" class="org.springframework.scheduling.quartz.JobDetailBean">
4、executeInternal方法中使用其参数来获得值。
protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
这样就解决了注入的对象为null的问题。网上找了好多找不到解决的办法,最终还得靠自己。
5、解决是解决了,但是过程中我需要用到事务操作。随之带来了很大的麻烦,毕竟项目用的都是Annotaion,再加上自己在ApplicationContext.xml中配置,造成了很多麻烦和异常。
6、放弃,转Annotation
通过 注解
来调度任务
1、
AnnotationQuartz类:
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class AnnotationQuartz {
}
2、
spring的ApplicationContext.xml中的配置:
只需要加上
<!--
<!--
3、(如果是web应用,那么需要再web.xml中加入)
<listener>
</listener>
通过 配置文件
来调度任务
1、
AnnotationQuartz类:
import org.springframework.stereotype.Component;
@Component(如果你的项目使用的是注解而不是配置文件中写bean,那么需要加上@Component,确保这个类已经注入)
public class AnnotationQuartz {
}
2、
spring的ApplicationContext.xml中的配置:
<task:scheduled-tasks>
</task:scheduled-tasks>
最后请注意 :(ApplicationContext.xml)
a)、需要在xmlns里面加入:
xmlns:task="http://www.springframework.org/schema/task"
b)、在xsi:schemaLocation中加入
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd(别忘了最后的引号)
cron表达式去搜吧,好多,我搜到了一些,如下:
<!--
一个cron表达式有到少6个(也可能是7个)由空格分隔的时间元素.从左到右,这些元素的定义如下:
-->