1. 介绍
cron是linux系统用来设置定期执行的任务,例如:每天晚上12点进行系统垃圾文件整理.
本篇文章主要的重点是cron描述定时任务的时间表达式该如何书写。
2. 格式
一个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,SEP MON-FRI 2002-2010
3. 特殊字符的介绍
*:表示所有可能值,用来选择当前字段可被允许的所有值,例如: 在分钟字段中到*
,则表示每分钟的意思;
? :表示无特定的值,可以简单的理解为“不考虑”,例如:你想在每个月的第10天做某项任务,但是你并不关心这天到底是一周的第几天,这时你就需要在”day-of-week”上面设置”?”;
- : 用来指定范围,例如: 在小时字段设置”10-12”,则表示10点,11点,12点;
, : 用来指定额外的值,例如:在day-of-week字段中设置”MON,WED,FRI”则表示星期一、星期二、以及星期五;
/ : 用来设置增量,例如:如何在秒的字段设置了”0/15”, 则表示: 0, 15, 30和45
L :表示最后的,用在”day-of-month”表示当月的最后一天,用在”day-of week”表示”7”(或”SAT”), 另外当用在”day-of-week”时,可以接数值,例如6L表示当月的最后一个星期五;
W (“weekday”) - 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”. So if the 15th is a Saturday, the trigger will fire on Friday the 14th. If the 15th is a Sunday, the trigger will fire on Monday the 16th. If the 15th is a Tuesday, then it will fire on Tuesday the 15th. However if you specify “1W” as the value for day-of-month, and the 1st is a Saturday, the trigger will fire on Monday the 3rd, as it will not ‘jump’ over the boundary of a month’s days. The ‘W’ character can only be specified when the day-of-month is a single day, not a range or list of days.
The ‘L’ and ‘W’ characters can also be combined in the day-of-month field to yield ‘LW’, which translates to “last weekday of the month”.
参考:
http://www.quartz-scheduler.org/documentation/quartz-1.x/tutorials/crontrigger