SimpleTrigger
如果需要计划一个任务在指定的时间执行,或者在指定的时间后以指定的间隔连续执行多次,比如希望在2005年1月12号上午11:22:54开始执行一个任务,在这之后每隔20分钟执行一次,共执行一次,这种情况下可以使用SimpleTrigger。
SimpleTrigger包含几个属性:开始时间,结束时间,重复次数和间隔。
重复次数可以是大于等于0,或者是常量值SimpleTrigger.REPEAT_INDEFINITELY,间隔必须大于等于0的长整数,单位是微秒。如果间隔为0表示并发执行重复次数。
如果不熟悉java.util.Calendar类,可能经常需要根据开始时间计算触发时间,org.quartz.helpers.TriggerUtils 可以帮助完成这些任务。
结束时间属性重写重复次数属性。如果希望创建一个触发器,每隔10秒执行一次,直到一个指定的时间,可以简单的指定结束时间, 重复次数值为REPEAT_INDEFINITELY。
CronTrigger
CronTrigger 支持比 SimpleTrigger 更具体的调度,而且也不是很复杂。基于 cron 表达式,CronTrigger 支持类似日历的重复间隔,而不是单一的时间间隔 —— 这相对 SimpleTrigger 而言是一大改进。
Cron 表达式包括以下 7 个字段:
秒
分
小时
月内日期
月
周内日期
年(可选字段)
Cron 触发器利用一系列特殊字符,如下所示:
反斜线(/)字符表示增量值。例如,在秒字段中“5/15”代表从第 5 秒开始,每 15 秒一次。
问号(?)字符和字母 L 字符只有在月内日期和周内日期字段中可用。问号表示这个字段不包含具体值。所以,如果指定月内日期,可以在周内日期字段中插入“?”,表示周内日期值无关紧要。字母 L 字符是 last 的缩写。放在月内日期字段中,表示安排在当月最后一天执行。在周内日期字段中,如果“L”单独存在,就等于“7”,否则代表当月内周内日期的最后一个实例。所以“0L”表示安排在当月的最后一个星期日执行。
在月内日期字段中的字母(W)字符把执行安排在最靠近指定值的工作日。把“1W”放在月内日期字段中,表示把执行安排在当月的第一个工作日内。
井号(#)字符为给定月份指定具体的工作日实例。把“MON#2”放在周内日期字段中,表示把任务安排在当月的第二个星期一。
星号(*)字符是通配字符,表示该字段可以接受任何可能的值。
Expression |
Meaning |
0 0 12 * * ? |
Fire at 12pm (noon) every day |
0 15 10 ? * * |
Fire at 10:15am every day |
0 15 10 * * ? |
Fire at 10:15am every day |
0 15 10 * * ? * |
Fire at 10:15am every day |
0 15 10 * * ? 2005 |
Fire at 10:15am every day during the year 2005 |
0 * 14 * * ? |
Fire every minute starting at 2pm and ending at 2:59pm, every day |
0 0/5 14 * * ? |
Fire every 5 minutes starting at 2pm and ending at 2:55pm, every day |
0 0/5 14,18 * * ? |
Fire every 5 minutes starting at 2pm and ending at 2:55pm, AND fire every 5 minutes starting at 6pm and ending at 6:55pm, every day |
0 0-5 14 * * ? |
Fire every minute starting at 2pm and ending at 2:05pm, every day |
0 10,44 14 ? 3 WED |
Fire at 2:10pm and at 2:44pm every Wednesday in the month of March. |
0 15 10 ? * MON-FRI |
Fire at 10:15am every Monday, Tuesday, Wednesday, Thursday and Friday |
0 15 10 15 * ? |
Fire at 10:15am on the 15th day of every month |
0 15 10 L * ? |
Fire at 10:15am on the last day of every month |
0 15 10 ? * 6L |
Fire at 10:15am on the last Friday of every month |
0 15 10 ? * 6L |
Fire at 10:15am on the last Friday of every month |
0 15 10 ? * 6L 2002-2005 |
Fire at 10:15am on every last friday of every month during the years 2002, 2003, 2004 and 2005 |
0 15 10 ? * 6#3 |
Fire at 10:15am on the third Friday of every month |
0 0 12 1/5 * ? |
Fire at 12pm (noon) every 5 days every month, starting on the first day of the month. |
0 11 11 11 11 ? |
Fire every November 11th at 11:11am. |