QuartZ中的Cron表达式

一个cron 表达式是由6或者7个以空格分隔的字段组成。字段能够包含任何允许值,伴随着特殊字符不同组合。这些字段如下所示:

字段名称 是否一定需要 允许的值 允许的特殊字符串
Seconds YES 0-59 , – * /
Minutes YES 0-59 , – * /
Hours YES 0-23 , – * /
Day of month YES 1-31 , – * ? / L W
Month YES 1-12 or JAN-DEC , – * /
Day of week YES 1-7 or SUN-SAT , – * ? / L #
Year NO empty, 1970-2099 , – * /

可见,一个简单的cron表达式可以如此* * * * ? *表达或者更复杂些,像这样

0/5 14,18,3-39,52 * ? JAN,MAR,SEPMON-FRI 2002-2010

特殊字符串说明

  • * (“所有的值”) – 意味着所有值。
  • ? (“无特殊值”) – 当你需要指定两个字段中的一个时,这个字符很有用。比如,如果我想在一个月中的特别的一天(可以是第10号之类的)触发我的触发器,但是我并不关心它是哪个星期执行。这样的话,可以在月份字段上设置0,星期字段上设置问号(?)。
  • (“指定区间”)-  用来指定区间。比如,“10-12”在小时字段中,这意味着“10点、11点和12点”
  • (“定额外的值”)- 用来指定额外的值。比如,在星期字段中,“MON,WED,FRI”表示“星期一,星期三,星期五”。
  • / (“递增”)-用来指定递增量。比如,在秒字段上,“0/15”表示“0秒、15秒、30秒和45秒”。
  • L (“最后”) –在两个字段上,它们有不同的含义。比如,在天数字段上,“L”值意味着“一个月的最后一天”–平年中2月份的28号,一月的31号等。如果使用在星期 字段中,它简单地意味着“7”或者“星期六”。当使用“L”时,那是很重要的,不去指定列表或者区间,因为你将获得令人困惑的结果。
  • W (“星期”) – 使用来指定星期中最靠近给予的天。例如,我在天数字段上指定了“15W”,这就意味着“这个月离15号最近的某个星期”。如果15号是星期天,它将在周六 的14号触发。如果15好是一个星期二,那么他将在15号的星期二触发。在天字段上,“W”不会跳跃过月份来触发执行。在天数字段上,“L”和“W”能够 结合使用,表示的意思是:“月份的最后一个星期”
  • # (“天数”) –用来指定一个月的某一天。比如,在星期字段上,“6#3”表示“每月的第三个星期五”(6表示星期五,#3表示这个月的第三个)。如果像“#3”指定的话,它将不会触发。

合法的字符串、月份的名字和星期的字母表示,这些都不是大小写敏感的。

下面有一个完全的例子:

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.