Spring与Quartz使用说明 job不同步执行(第一个job完成后才开始第二个job)
转自:http://blog.sina.com.cn/s/blog_675e9aeb0100qghp.html
最 近因为项目后台需要使用一个线程去定时跑一些任务,所以看了一下Spring和Quartz的使用与集成。例如发短信、邮件。根据实际使用,此集成使用比 自己去写线程方便和灵活,可以不用代码实现复杂的计划任务,如“1月份的每周三、周五的早上9点至10点每5钟一次任务”。所以分享一下。
Quartz官方网址:http://www.quartz-scheduler.org/
集成方法
集成起来比较简单,对线程无需任何理解,Spring手册上也有清楚的说明。只需写一个POJO,其余的都是配置,而且若使用CronTriggerBean,可以配置很复杂的任务调度。
1.编写一个普通的JAVA类
根据业务,写一个简单的JAVA类,和普通的类没有区别。并配置到Spring配置文件上中。例:
<bean id="vcSMSProcessService" class="com.sinoprof.vc.sms.service.impl.MessageProcessServiceImpl"> <property name="vcSMSLocalDAO" ref="vcSMSLocalDAO"/> <property name="vcSMSOAService" ref="vcSMSOAService"/> <property name="vcSMSConfig" ref="vcSMSConfig"/> <property name="vcSMSGateWayService" ref="vcSMSGateWayService"/> </bean> |
2.使用MethodInvokingJobDetailFactoryBean建立任务
只需要配置即可,配置信息示例如下:
<bean id="jobTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject"> <ref bean="vcSMSProcessService"/> </property> <property name="targetMethod"> <value>sendMessages</value> </property> <property name="concurrent"> <value>false</value> </property> </bean> |
说明:
targetObject |
目标对象,即需要定时执行的POJO |
targetMethod |
目标方法,即需要定时执行的POJO方法 |
concurrent |
默认情况下,Quartz Jobs 是无状态的,可能导致jobs之间互相的影响,如果你为相同的JobDetail指定两个Trigger,很可能当第一个job完成之前,第二个job就 开始了。如果Jobdetail实现了Stateful接口,就不会发生这样的事情。第二个job将不会在第一个job完成之前开始。为了使得jobs不 并发运行,设置concurrent标记为false |
3.使用CronTriggerBean建立规则,调度任务
<bean id="jobTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail"> <ref bean="jobTask"/> </property> <property name="cronExpression"> <value>0 0/5 8-18 ? * 2-6 *</value> </property> </bean> |
说明:
jobDetail |
任务详情,即所需要调度的任务 |
cronExpression |
调用规则,即什么时候调用。详细说明见附录1 |
4.使用SchedulerFactoryBean包装任务
<bean id="startQuartz" lazy-init="false" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="jobTrigger"/> </list> </property> <property name="autoStartup" value="true"/> <property name="schedulerName" value="cronScheduler"/> </bean> |
说明:
triggers |
触发器,调用哪些任务 |
autoStartup |
是否自动启动,该Bean被初始化后是否自动启动定时任务。 Set whether to automatically start the scheduler after initialization. |
schedulerName |
给这个计划设定一个名称。 Set the name of the Scheduler to fetch from the SchedulerFactory. |
更多使用细节可以参考Spring文档和Quartz文档
附录1:CronTrigger说明
如果需要复杂的任务计划调度,像日历样式的任务,而不是简单的时间间隔调度,需要使用CronTrigger,SimpleTrigger满足不了需求。
用CronTrigger,你可以定义任务计划像“每周五的中午”,或“每个工作日的早上9:30”,甚至可以定义“1月份的每周一、周三、周五早上9:00至10:00,每5分钟一次”。
虽然如此,像SimpleTrigger一样,CronTrigger仍有startTime属性定义计划的开始时间,endTime(可选)属性定义计划的中止时间。
Cron Expressions
Cron-Expressions是用来配置CronTrigger实例。Cron-Expressions是由七段子表达式组成的字符串,描述各个细节计划。这些子字符串由空格分开,每个子字符串表示一个域,分别为:
1 秒
2 分
3 时
4 几号
5 月份
6 星期几
7 年(可选域)
例如:"0 0 12 ? * WED"-表示每周三12:00:00pm"。
其中每个独立的子表达式都可以用范围或者列表表示。例如:
前例的”WED“也可以写成:
"MON-FRI"(范围表示)
"MON,WED,FRI"(列表表示)
"MON-WED,SAT"(范围加列表)
通配符(*)可以用来表示某个子表达式域的每一个可能的值。因此,“*”号用在月份里,表示每月。用在星期几里,表示一周中的每天。
每个子表达式域都有一组有效的值,这些值都是显然意见的。例:用0-59表示秒和分,用0到23表示小时。几号用0-31中的任何值,但是要小心每月的天数。月份指定的值应该是0至11,也可以用字符串 JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV和DEC表示。星期几用1到7表示(1=星期天),或用英文字符表示:SUN,MON,TUE,WED,THU,FRI和SAT。
字 符“/”用来表示增量的值。例如:如果用“0/15”表示分,就表示从一个小时的0分开始,在这小时内每隔15分钟一次。如果用"3/20"表示分,则表 示从一个小时的3分开始,在这小时内每隔20分钟一次。也可以用“3,23,43”表示。注意"*/35"并不是表示每35分钟,而是表示从一个小时的0 分开始,每隔35分钟一次,相当于"0,35"。
“?"号允许用在几号和星期几的子字符串域中,用来说明没有指定值。
“L”字 符允许用在几号和星期几域中,是"last"的缩写。“L”用在几号里意思是这个月的最后一天,如果是1月就指31号,如果是闰年的2月就是28号。如果 用在星期几里,他就是表示“7”或者“SAT”(星期六)。但是如果L用在一个值的后面联合表示星期几域,就表示“这个月最后一个星期几”。例 如:“6L”或“FRIL”表示这个月的最后一个星期五。同样也可以用一个偏移变量表示距离某个月最后一天的天数。例如:“L-3”表示某月最后一天的倒 数第三天。但用“L“字符时,不要将“L”用在列表或范围中,那样你会混淆或者获得不是预期的结果。
“W”用来指定某一号最近的工作日(星期一至五),例如:“15W”放在几号里,表示这个月15号最近的一个工作日。
“#”号用指定某月第几个工作日,例如:“6#3”或“FRI#3”放在星期几域中,表示这个月第三个星期五。
下面是一些表达式的样例,你可以从JavaDoc中找到更多的例子。
Cron Expressions示例
例1-一个表达式表示每5分钟。
"0 0/5 * * * ?"
例2——表示每分钟的10秒后,每5钟一次(如:10:00:10 am,10:05:10 am,等等)
"10 0/5 * * * ?"
例3——表示运行在每个星期三,星期五的10:30,11:30,12:30 and 13:30
"0 30 10-13 ? * WED,FRI"
例4——表示每月的5号和20号的早8点至早10点每30分钟一次。
"0 0/30 8-10 5,20 * ?"
注意,有些计划调度需求如果用一个触发器会很复杂,例如:“早9:00至10:00每5分钟,下午1:00至10:00每20分钟”,这种情况下可以是单的创建两个触发器同时运行一个JOB
以下是附录的原文,有兴趣可以自己去看。
Lesson 6: CronTrigger
CronTrigger is often more useful than SimpleTrigger, if you need a job-firing schedule that recurs based on calendar-like notions, rather than on the exactly specified intervals of SimpleTrigger.
With CronTrigger, you can specify firing-schedules such as "every Friday at noon", or "every weekday and 9:30 am", or even "every 5 minutes between 9:00 am and 10:00 am on every Monday, Wednesday and Friday during January".
Even so, like SimpleTrigger, CronTrigger has a startTime which specifies when the schedule is in force, and an (optional) endTime that specifies when the schedule should be discontinued.
Cron Expressions
Cron-Expressions are used to configure instances of CronTrigger. Cron-Expressions are strings that are actually made up of seven sub-expressions, that describe individual details of the schedule. These sub-expression are separated with white-space, and represent:
1 Seconds
2 Minutes
3 Hours
4 Day-of-Month
5 Month
6 Day-of-Week
7 Year (optional field)
An example of a complete cron-expression is the string "0 0 12 ? * WED" - which means "every Wednesday at 12:00:00 pm".
Individual sub-expressions can contain ranges and/or lists. For example, the day of week field in the previous (which reads "WED") example could be replaced with "MON-FRI", "MON,WED,FRI", or even "MON-WED,SAT".
Wild-cards (the '*' character) can be used to say "every" possible value of this field. Therefore the '*' character in the "Month" field of the previous example simply means "every month". A '*' in the Day-Of-Week field would therefore obviously mean "every day of the week".
All of the fields have a set of valid values that can be specified. These values should be fairly obvious - such as the numbers 0 to 59 for seconds and minutes, and the values 0 to 23 for hours. Day-of-Month can be any value 0-31, but you need to be careful about how many days are in a given month! Months can be specified as values between 0 and 11, or by using the strings JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV and DEC. Days-of-Week can be specified as values between 1 and 7 (1 = Sunday) or by using the strings SUN, MON, TUE, WED, THU, FRI and SAT.
The '/' character can be used to specify increments to values. For example, if you put '0/15' in the Minutes field, it means 'every 15th minute of the hour, starting at minute zero'. If you used '3/20' in the Minutes field, it would mean 'every 20th minute of the hour, starting at minute three' - or in other words it is the same as specifying '3,23,43' in the Minutes field. Note the subtlety that "*/35" does not mean "every 35 minutes" - it mean "every 35th minute of the hour, starting at minute zero" - or in other words the same as specifying '0,35'.
The '?' character is allowed for the day-of-month and day-of-week fields. It is used to specify "no specific value". This is useful when you need to specify something in one of the two fields, but not the other. See the examples below (and CronTrigger JavaDoc) for clarification.
The 'L' character is allowed for the day-of-month and day-of-week fields. This character is short-hand for "last", but it has different meaning in each of the two fields. For example, the value "L" in the day-of-month field means "the last day of the month" - day 31 for January, day 28 for February on non-leap years. If used in the day-of-week field by itself, it simply means "7" or "SAT". But if used in the day-of-week field after another value, it means "the last xxx day of the month" - for example "6L" or "FRIL" both mean "the last friday of the month". You can also specify an offset from the last day of the month, such as "L-3" which would mean the third-to-last day of the calendar month. When using the 'L' option, it is important not to specify lists, or ranges of values, as you'll get confusing/unexpected results.
The 'W' is used to specify the weekday (Monday-Friday) nearest the given day. As an example, if you were to specify "15W" as the value for the day-of-month field, the meaning is: "the nearest weekday to the 15th of the month".
The '#' is used to specify "the nth" XXX weekday of the month. For example, the value of "6#3" or "FRI#3" in the day-of-week field means "the third Friday of the month".
Here are a few more examples of expressions and their meanings - you can find even more in the JavaDoc for org.quartz.CronExpression
Example Cron Expressions
CronTrigger Example 1 - an expression to create a trigger that simply fires every 5 minutes
"0 0/5 * * * ?"
CronTrigger Example 2 - an expression to create a trigger that fires every 5 minutes, at 10 seconds after the minute (i.e. 10:00:10 am, 10:05:10 am, etc.).
"10 0/5 * * * ?"
CronTrigger Example 3 - an expression to create a trigger that fires at 10:30, 11:30, 12:30, and 13:30, on every Wednesday and Friday.
"0 30 10-13 ? * WED,FRI"
CronTrigger Example 4 - an expression to create a trigger that fires every half hour between the hours of 8 am and 10 am on the 5th and 20th of every month. Note that the trigger will NOT fire at 10:00 am, just at 8:00, 8:30, 9:00 and 9:30
"0 0/30 8-9 5,20 * ?"
Note that some scheduling requirements are too complicated to express with a single trigger - such as "every 5 minutes between 9:00 am and 10:00 am, and every 20 minutes between 1:00 pm and 10:00 pm". The solution in this scenario is to simply create two triggers, and register both of them to run the same job.
Building CronTriggers
CronTrigger instances are built using TriggerBuilder (for the trigger's main properties) and CronScheduleBuilder (for the CronTrigger-specific properties). To use these builders in a DSL-style, use static imports:
import static org.quartz.TriggerBuilder.*;
import static org.quartz.CronScheduleBuilder.*;
import static org.quartz.DateBuilder.*:
Build a trigger that will fire every other minute, between 8am and 5pm, every day:
trigger = newTrigger()
.withIdentity("trigger3", "group1")
.withSchedule(cronSchedule("0 0/2 8-17 * * ?"))
.forJob("myJob", "group1")
.build();
Build a trigger that will fire daily at 10:42 am:
trigger = newTrigger()
.withIdentity("trigger3", "group1")
.withSchedule(dailyAtHourAndMinute(10, 42))
.forJob(myJobKey)
.build();
- or -
trigger = newTrigger()
.withIdentity("trigger3", "group1")
.withSchedule(cronSchedule("0 42 10 * * ?"))
.forJob(myJobKey)
.build();
Build a trigger that will fire on Wednesdays at 10:42 am, in a TimeZone other than the system's default:
trigger = newTrigger()
.withIdentity("trigger3", "group1")
.withSchedule(weeklyOnDayAndHourAndMinute(DateBuilder.WEDNESDAY, 10, 42))
.forJob(myJobKey)
.inTimeZone(TimeZone.getTimeZone("America/Los_Angeles"))
.build();
- or -
trigger = newTrigger()
.withIdentity("trigger3", "group1")
.withSchedule(cronSchedule("0 42 10 ? * WED"))
.inTimeZone(TimeZone.getTimeZone("America/Los_Angeles"))
.forJob(myJobKey)
.build();
CronTrigger Misfire Instructions
The following instructions can be used to inform Quartz what it should do when a misfire occurs for CronTrigger. (Misfire situations were introduced in the More About Triggers section of this tutorial). These instructions are defined as constants on CronTrigger itself (including JavaDoc describing their behavior). The instructions include:
Misfire Instruction Constants of CronTrigger
MISFIRE_INSTRUCTION_IGNORE_MISFIRE_POLICY
MISFIRE_INSTRUCTION_DO_NOTHING
MISFIRE_INSTRUCTION_FIRE_NOW
All triggers also have the Trigger.MISFIRE_INSTRUCTION_SMART_POLICY instruction available for use, and this instruction is also the default for all trigger types. The 'smart policy' instruction is interpreted by CronTrigger as MISFIRE_INSTRUCTION_FIRE_NOW. The JavaDoc for the CronTrigger.updateAfterMisfire() method explains the exact details of this behavior.
When building CronTriggers, you specify the misfire instruction as part of the simple schedule (via CronSchedulerBuilder):
trigger = newTrigger()
.withIdentity("trigger3", "group1")
.withSchedule(cronSchedule("0 0/2 8-17 * * ?")
..withMisfireHandlingInstructionFireAndProceed())
.forJob("myJob", "group1")
.build();