---
title: "Spring的定时器功能"
author: "背包客"
date: "2013-04-05T00:56:19Z"
tags: ["Spring", "Timer", "quartz"]
categories: ["企业架构"]
slug: "spring"
draft: false
lastmod: "2013-04-05T01:06:02Z"
id: 1842149
url: "https://lchangw.iteye.com/blog/1842149"
---

spring支持jdk内置的Timer类和Quartz Scheduler，两种Spring定时器的实现方式各有优点，可结合具体项目考虑是否采用。

1.Java Timer定时

首先继承java.util.TimerTask类实现run方法

import java.util.TimerTask;    
public class EmailReportTask extends TimerTask{    
    @Override    
    public void run() {    
        ...    
    }      
}    
在Spring定义

...

配置Spring定时器

&lt;bean id="scheduleReportTask" class="org.springframework.scheduling.timer.ScheduledTimerTask"&gt;    
&lt;property name="timerTask" ref="reportTimerTask" /&gt;    
&lt;property name="period"&gt;    
&lt;value&gt;86400000value&gt;    
property&gt;    
bean&gt;    
timerTask属性告诉ScheduledTimerTask运行哪个。86400000代表24个小时

启动Spring定时器

Spring的TimerFactoryBean负责启动定时任务

&lt;bean class="org.springframework.scheduling.timer.TimerFactoryBean"&gt;    
&lt;property name="scheduledTimerTasks"&gt;    
   &lt;list&gt;&lt;ref bean="scheduleReportTask"/&gt;list&gt;    
property&gt;    
bean&gt;    
scheduledTimerTasks里显示一个需要启动的定时器任务的列表。    
可以通过设置delay属性延迟启动    
&lt;bean id="scheduleReportTask" class="org.springframework.scheduling.timer.ScheduledTimerTask"&gt;    
&lt;property name="timerTask" ref="reportTimerTask" /&gt;    
&lt;property name="period"&gt;    
&lt;value&gt;86400000value&gt;    
property&gt;    
&lt;property name="delay"&gt;    
&lt;value&gt;3600000value&gt;    
property&gt;    
bean&gt;    
这个任务我们只能规定每隔24小时运行一次，无法精确到某时启动

 

2.Quartz定时器

记得需继承QuartzJobBean类实现executeInternal方法

spring的定时器功能，它不仅实现起来方便，功能强大，而且在web开发时正好配合spring框架使用。

   

介绍spring的定时器，当然要先介绍配置文件applicationContext.xml了。

 

&lt;bean name="job" class="org.springframework.scheduling.quartz.JobDetailBean"&gt;

     &lt;property name="jobClass"&gt;

         &lt;value&gt;jaoso.news.web.action.JobAction&lt;/value&gt;

     &lt;/property&gt;

     &lt;property name="jobDataAsMap"&gt;

         &lt;map&gt;

             &lt;entry key="timeout"&gt;

                 &lt;value&gt;10&lt;/value&gt;

              &lt;/entry&gt;

         &lt;/map&gt;

     &lt;/property&gt;

&lt;/bean&gt;

 

说明：org.springframework.scheduling.quartz.JobDetailBean是spring对你的类进行调度的代理，在jobClass中要指定你的任务类（com.yangsq.web.action.JobAction），在jobDataAsMap中向你的任务类中注入一些信息，当然也可以reference一个，不要忘记在你的任务里加入这些属性及set方法。

timeout属性设定了当服务器启动后过10秒钟首次调用你的JobAction。

 

&lt;bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"&gt;

     &lt;property name="jobDetail"&gt;

         &lt;ref bean="job"/&gt;

     &lt;/property&gt;

     &lt;property name="cronExpression"&gt;

         &lt;value&gt;0 0/2 * * * ?&lt;/value&gt;

     &lt;/property&gt;

&lt;/bean&gt;

 

说明：org.springframework.scheduling.quartz.CronTriggerBean是spring提供的触发器，在这个触发器中设定了要触发的job（jobDetail属性设定了先前定义的bean），同时设定了触发时间（cronExpression）---每隔两分钟（0 0/2 * * * ?），这个的设定方式最后会说明。

 

&lt;bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"&gt;

     &lt;property name="triggers"&gt;

         &lt;list&gt;

             &lt;ref local="cronTrigger"/&gt;

         &lt;/list&gt;

     &lt;/property&gt;

&lt;/bean&gt;

 

说明：org.springframework.scheduling.quartz.SchedulerFactoryBean这是一个spring的工厂bean，在他的triggers属性列表中加入刚才定义的触发器，这里可以定义多个触发器（list嘛）。

 

好了，配置文件就介绍完了，该介绍com.yangsq.web.action.JobAction类了，

 

引入包：

 

[![spring中的定时器功能 - 邱园杰 - 邱园杰的博客](http://img.blog.163.com/photo/iavpdEzFY39yi3drK8zLLQ==/2831638265710227021.jpg)](http://blog.sina.com.cn/main/html/showpic.html#url=http://s1.album.sina.com.cn/pic/4b86f2ee02000etc)

说明：QuartzJobBean是spring自带的，把spring的jar包加入就行了，但是前两个包要去下了，呵呵，google吧。

 

 

 

[![spring中的定时器功能 - 邱园杰 - 邱园杰的博客](http://img.blog.163.com/photo/lC2v32JW7SNMPsO4g8g2ng==/2831638265710227022.jpg)](http://blog.sina.com.cn/main/html/showpic.html#url=http://s2.album.sina.com.cn/pic/4b86f2ee02000etd)

[![spring中的定时器功能 - 邱园杰 - 邱园杰的博客](http://img.blog.163.com/photo/qr35Mmfd1CxBawy8Xfc9Ow==/2831638265710227023.jpg)](http://blog.sina.com.cn/main/html/showpic.html#url=http://s3.album.sina.com.cn/pic/4b86f2ee02000ete)

 

当然要继承QuartzJobBean了，但是光extends不行，必须要重载他的executeInternal方法

[![spring中的定时器功能 - 邱园杰 - 邱园杰的博客](http://img.blog.163.com/photo/0H2JxZPZDhS_bMpBME0VsA==/2831638265710227024.jpg)](http://blog.sina.com.cn/main/html/showpic.html#url=http://s4.album.sina.com.cn/pic/4b86f2ee02000etf)

 

 

好了，一个spring的时间调度完成了。

 

附：时间配置说明

 

sping定时器的时间配置十分强大，下面将介绍如何进行配置。

[![spring中的定时器功能 - 邱园杰 - 邱园杰的博客](http://img.blog.163.com/photo/Ix4LPZxPYyWEz2mOTsbjjQ==/2831638265710227026.jpg)](http://blog.sina.com.cn/main/html/showpic.html#url=http://s5.album.sina.com.cn/pic/4b86f2ee02000etg)

[![spring中的定时器功能 - 邱园杰 - 邱园杰的博客](http://img.blog.163.com/photo/8kDgH4CVBDqzQV8vQDTPaw==/2831638265710227027.jpg)](http://blog.sina.com.cn/main/html/showpic.html#url=http://s6.album.sina.com.cn/pic/4b86f2ee02000eth)