Spring定时器的两种实现方式
Spring定时器的两种实现方式,包括Java Timer定时和Quartz定时器,两种Spring定时器的实现方式各有优点,可结合具体项目考虑是否采用。
?
1.Java Timer定时
首先继承java.util.TimerTask类实现run方法
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean ref="reportTimerTask" />??
?? <property name="period">
????????? <value>30000</value>??
?? </property>??
?? <property name="delay">
????????? <value>60000</value>??
???</property>??
</bean>
<bean id="reportTimerTask" ref="playService"></property>
??????? <property name="advertiseService" ref="advertiseService"></property>
</bean>?
??
</beans>
?
这个任务我们只能规定每隔24小时运行一次,无法精确到某时启动。
?
?
?
?
?
2.Quartz定时器
首先继承QuartzJobBean类实现executeInternal方法
???? import org.quartz.JobExecutionContext;??
???? import org.quartz.JobExecutionException;??
???? import org.springframework.scheduling.quartz.QuartzJobBean;
???
???? public class EmailReportJob extends QuartzJobBean{
?
??????????????? protected void executeInternal(JobExecutionContext arg0)??
??????????????????????????????? throws JobExecutionException {???
??????????????? }??
???? }?
?
在Spring中定义
<bean id="reportJob" class="org.springframework.scheduling.quartz.JobDetailBean">??
?????? <property name="jobClass">
??????????????????? <value>EmailReportJob</value>
???????</property>??
?????? <property name="jobDataAsMap">???
??????????????????? <map>
??????????????????????? <entry key="courseService"><ref bean="courseService"/> </entry>
??????????????????? </map>
??????? </property>
</bean>
在这里我们并没有直接声明一个EmailReportJob Bean,而是声明了一个JobDetailBean。这个是Quartz的特点。JobDetailBean是Quartz的org.quartz.JobDetail的子类,它要求通过jobClass属性来设置一个Job对象。
使用Quartz的JobDetail中的另一个特别之处是EmailReportJob的courseService属性是间接设置的。JobDetail的jobDataAsMap属性接受一个Map,包括设置给jobClass的各种属性,当。JobDetailBean实例化时,它会将courseService Bean注入到EmailReportJob 的courseService 属性中。
?
启动定时器
Quartz的org.quartz.Trigger类描述了何时及以怎样的频度运行一个Quartz工作。Spring提供了两个触发器SimpleTriggerBean和CronTriggerBean。
SimpleTriggerBean与scheduledTimerTasks类似。指定工作的执行频度,模仿scheduledTimerTasks配置 .
<bean id="simpleReportTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">??
??????????? <property name="jobDetail" ref="reprotJob" />??
????????????<property name="startDelay">??
??????????????????? <value>360000value>??
????????????</property>??
??????????? <property name="repeatInterval">
????????????????????<value>86400000value>??
?????????????</property>??
</bean>??
startDelay也是延迟1个小时启动
?
CronTriggerBean指定工作的准确运行时间
<bean id="cronReportTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">??
?????????? <property name="jobDetail" ref="reprotJob" />??
?????????? <property name="cronExpression">??
?????????????????????? <value>0 0 6 * * ?value>??
???????????</property>??
<bean>
属性cronExpression告诉何时触发。最神秘就是cron表达式:
?
?
?
?
?
?
?
?
?