有两种流行Spring定时器配置:Java的Timer类和OpenSymphony的Quartz。1.Java Timer定时

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

   1. import java.util.TimerTask;

2.publicclassEmailReportTaskextendsTimerTask{

3.@Override

4.publicvoidrun(){

5....

6.}

   7. }

在Spring定义

...

配置Spring定时器

   1. < bean  id = "scheduleReportTask"  class = "org.springframework.scheduling.timer.ScheduledTimerTask" >

2.<propertyname="timerTask"ref="reportTimerTask"/>

3.<propertyname="period">

4.<value>86400000value>

5.property>

   6. bean >

timerTask属性告诉ScheduledTimerTask运行哪个。86400000代表24个小时

启动Spring定时器

Spring的TimerFactoryBean负责启动定时任务

< bean  class = "org.springframework.scheduling.timer.TimerFactoryBean" >

<propertyname="scheduledTimerTasks">

<list><refbean="scheduleReportTask"/></list>

<property>

</bean>

scheduledTimerTasks里显示一个需要启动的定时器任务的列表。

可以通过设置delay属性延迟启动

<beanid="scheduleReportTask"class="org.springframework.scheduling.timer.ScheduledTimerTask">

<propertyname="timerTask"ref="reportTimerTask"/>

<propertyname="period">

<value>86400000</value>

<property>

<propertyname="delay">

<value>3600000value>

</property>

</bean>

这个任务我们只能规定每隔24小时运行一次,无法精确到某时启动

2.Quartz定时器

Quartz下载地址:http://www.opensymphony.com/quartz

首先继承QuartzJobBean类实现executeInternal方法

import  org.quartz.JobExecutionContext;

importorg.quartz.JobExecutionException;

importorg.springframework.scheduling.quartz.QuartzJobBean;

publicclassEmailReportJobextendsQuartzJobBean{

protectedvoidexecuteInternal(JobExecutionContextarg0)

throwsJobExecutionException{

...

}

}

在Spring中定义

< bean  id = "reportJob"  class = "org.springframework.scheduling.quartz.JobDetailBean" >

<propertyname="jobClass">

<value>EmailReportJobvalue>

property>

<propertyname="jobDataAsMap">

<map>

<entrykey="courseService">

<refbean="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配置 .

startDelay也是延迟1个小时启动

CronTriggerBean指定工作的准确运行时间

属性cronExpression告诉何时触发。最神秘就是cron表达式:

Linux系统的计划任务通常有cron来承担。一个cron表达式有至少6个(也可能7个)有空格分隔的时间元素。从左到右:

1.秒2.分3.小时4.月份中的日期(1-31)5.月份(1-12或JAN-DEC)6.星期中的日期(1-7或SUN-SAT)7.年份(1970-2099)

每个元素都显示的规定一个值(如6),一个区间(9-12),一个列表(9,11,13)或一个通配符(*)。因为4和6这两个元素是互斥的,因此应该通过设置一个问号(?)来表明不想设置的那个字段,“/”如果值组合就表示重复次数(10/6表示每10秒重复6次)。

启动定时器

triggers属性接受一组触发器。

秒 0-59 , - * /
分 0-59 , - * /
小时 0-23 , - * /
日期 1-31 , - * ? / L W C
月份 1-12 或者 JAN-DEC , - * /
星期 1-7 或者 SUN-SAT , - * ? / L C #
年(可选) 留空, 1970-2099 , - * /

The'*'characterisusedtospecifyallvalues.Forexample,"*"intheminutefieldmeans"everyminute".

“*”字符被用来指定所有的值。如:”*“在分钟的字段域里表示“每分钟”。

The'?'characterisallowedfortheday-of-monthandday-of-weekfields.Itisusedtospecify'nospecificvalue'.Thisisusefulwhenyouneedtospecifysomethinginoneofthetwofileds,butnottheother.Seetheexamplesbelowforclarification.

“?”字符只在日期域和星期域中使用。它被用来指定“非明确的值”。当你需要通过在这两个域中的一个来指定一些东西的时候,它是有用的。看下面的例子你就会明白。

月份中的日期和星期中的日期这两个元素时互斥的一起应该通过设置一个问号(?)来表明不想设置那个字段

The'-'characterisusedtospecifyrangesForexample"10-12"inthehourfieldmeans"thehours10,11and12".

“-”字符被用来指定一个范围。如:“10-12”在小时域意味着“10点、11点、12点”。

The','characterisusedtospecifyadditionalvalues.Forexample"MON,WED,FRI"intheday-of-weekfieldmeans"thedaysMonday,Wednesday,andFriday".

“,”字符被用来指定另外的值。如:“MON,WED,FRI”在星期域里表示”星期一、星期三、星期五”.

The'/'characterisusedtospecifyincrements.Forexample"0/15"inthesecondsfieldmeans"theseconds0,15,30,and45".And"5/15"inthesecondsfieldmeans"theseconds5,20,35,and50".Specifying'*'beforethe'/'isequivalenttospecifying0isthevaluetostartwith.Essentially,foreachfieldintheexpression,thereisasetofnumbersthatcanbeturnedonoroff.Forsecondsandminutes,thenumbersrangefrom0to59.Forhours0to23,fordaysofthemonth0to31,andformonths1to12.The"/"charactersimplyhelpsyouturnonevery"nth"valueinthegivenset.Thus"7/6"inthemonthfieldonlyturnsonmonth"7",itdoesNOTmeanevery6thmonth,pleasenotethatsubtlety.

The'L'characterisallowedfortheday-of-monthandday-of-weekfields.Thischaracterisshort-handfor"last",butithasdifferentmeaningineachofthetwofields.Forexample,thevalue"L"intheday-of-monthfieldmeans"thelastdayofthemonth"-day31forJanuary,day28forFebruaryonnon-leapyears.Ifusedintheday-of-weekfieldbyitself,itsimplymeans"7"or"SAT".Butifusedintheday-of-weekfieldafteranothervalue,itmeans"thelastxxxdayofthemonth"-forexample"6L"means"thelastfridayofthemonth".Whenusingthe'L'option,itisimportantnottospecifylists,orrangesofvalues,asyou'llgetconfusingresults.

L是‘last’的省略写法可以表示day-of-month和day-of-week域,但在两个字段中的意思不同,例如day-of-month域中表示一个月的最后一天,

如果在day-of-week域表示‘7’或者‘SAT’,如果在day-of-week域中前面加上数字,它表示一个月的最后几天,例如‘6L’就表示一个月的最后一个

星期五,

The'W'characterisallowedfortheday-of-monthfield.Thischaracterisusedtospecifytheweekday(Monday-Friday)nearestthegivenday.Asanexample,ifyouweretospecify"15W"asthevaluefortheday-of-monthfield,themeaningis:"thenearestweekdaytothe15thofthemonth".Soifthe15thisaSaturday,thetriggerwillfireonFridaythe14th.Ifthe15thisaSunday,thetriggerwillfireonMondaythe16th.Ifthe15thisaTuesday,thenitwillfireonTuesdaythe15th.Howeverifyouspecify"1W"asthevalueforday-of-month,andthe1stisaSaturday,thetriggerwillfireonMondaythe3rd,asitwillnot'jump'overtheboundaryofamonth'sdays.The'W'charactercanonlybespecifiedwhentheday-of-monthisasingleday,notarangeorlistofdays

.

The'L'and'W'characterscanalsobecombinedfortheday-of-monthexpressiontoyield'LW',whichtranslatesto"lastweekdayofthemonth".

The'#'characterisallowedfortheday-of-weekfield.Thischaracterisusedtospecify"thenth"XXXdayofthemonth.Forexample,thevalueof"6#3"intheday-of-weekfieldmeansthethirdFridayofthemonth(day6=Fridayand"#3"=the3rdoneinthemonth).Otherexamples:"2#1"=thefirstMondayofthemonthand"4#5"=thefifthWednesdayofthemonth.Notethatifyouspecify"#5"andthereisnot5ofthegivenday-of-weekinthemonth,thennofiringwilloccurthatmonth.

The'C'characterisallowedfortheday-of-monthandday-of-weekfields.Thischaracterisshort-handfor"calendar".Thismeansvaluesarecalculatedagainsttheassociatedcalendar,ifany.Ifnocalendarisassociated,thenitisequivalenttohavinganall-inclusivecalendar.Avalueof"5C"intheday-of-monthfieldmeans"thefirstdayincludedbythecalendaronorafterthe5th".Avalueof"1C"intheday-of-weekfieldmeans"thefirstdayincludedbythecalendaronoraftersunday".

关于cronExpression的介绍:

 

字段允许值允许的特殊字符

秒0-59,-*/

分0-59,-*/

小时0-23,-*/

日期1-31,-*?/LWC

月份1-12或者JAN-DEC,-*/

星期1-7或者SUN-SAT,-*?/LC#

年(可选)留空,1970-2099,-*/

表达式意义

"0012**?"每天中午12点触发

"01510?**"每天上午10:15触发

"01510**?"每天上午10:15触发

"01510**?*"每天上午10:15触发

"01510**?2005"2005年的每天上午10:15触发

"0*14**?"在每天下午2点到下午2:59期间的每1分钟触发

"00/514**?"在每天下午2点到下午2:55期间的每5分钟触发

"00/514,18**?"在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发

"00-514**?"在每天下午2点到下午2:05期间的每1分钟触发

"010,4414?3WED"每年三月的星期三的下午2:10和2:44触发

"01510?*MON-FRI"周一至周五的上午10:15触发

"0151015*?"每月15日上午10:15触发

"01510L*?"每月最后一日的上午10:15触发

"01510?*6L"每月的最后一个星期五上午10:15触发

"01510?*6L2002-2005"2002年至2005年的每月的最后一个星期五上午10:15触发

"01510?*6#3"每月的第三个星期五上午10:15触发

每天早上6点

06***

每两个小时

0*/2***

晚上11点到早上8点之间每两个小时,早上八点

023-7/2,8***

每个月的4号和每个礼拜的礼拜一到礼拜三的早上11点

0114*1-3

1月1日早上4点

0 4 1 1 *

0 0/2 8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23 * * ? 每天8点到23点间每2分钟执行一次

quartz的高级特性不仅如此

1数据库存储

2集群支持

3数据库持久化任务,trigger

4trigger的停止,运行

5任务的任意添加

6比corntrigger更详尽的任务安排

7线程的内部数据交换