CRON expression

cron expression

不知道中文如何翻译,时间条件表达式?。。。
相对正则表达式,这种表达式在命令行工具以及一些开发框架上,都很常见,用来做为定时任务的时间的时间设定
例如:

  • command crontab
  • spring schedule task

都有使用过这种表达式

cron expression 详解

每个域的意义

1
2
3
4
5
6
7
8
9
10
* * * * * * *
| | | | | | |
| | | | | | +-- Year (range: 1970-2099)
| | | | | +---- Day of the Week (range: 1-7 or SUN-SAT)
| | | | +------ Month of the Year (range: 0-11 or JAN-DEC)
| | | +-------- Day of the Month (range: 1-31)
| | +---------- Hour (range: 0-23)
| +------------ Minute (range: 0-59)
+-------------- Second (range: 0-59)

每个域能赋值的情况

1
2
3
4
5
6
7
8
Field Name Mandatory Allowed Values Allowed Special Characters
Seconds YES 0-59 , - * /
Minutes YES 0-59 , - * /
Hours YES 0-23 , - * /
Day of month YES 1-31 , - * ? / L W //allowed '?'
Month YES 1-12 or JAN-DEC , - * /
Day of week YES 1-7 or SUN-SAT , - * ? / L # //allowed '?'
Year NO empty, 1970-2099 , - * /

注意能使用字符?的域有一个月的某天和一周的某天

实例

example 1

1
0 0 13/2 1/1 * * *

example2

1
0 0 0/1 1/1 * ? *

好像不是那么简单吧,出现了特殊字符,下面说明这些特殊字符的意义。

特殊字符

  • /
1
2
3
4
used to specify increments.
For example, “0/15” in the seconds field means “the seconds 0, 15, 30, and 45”. And “5/15” in the seconds field means “the seconds 5, 20, 35, and 50”.
You can also specify ‘/’ after the ‘’ character - in this case ‘’ is equivalent to having ‘0’ before the ‘/’.
‘1/3’ in the day-of-month field means “fire every 3 days starting on the first day of the month”.
  • n/m means start at XX n and repeat each m XX

  • * (“all values”)

    1
    used to select all values within a field. For example, “” in the minute field means *“every minute”.
  • ? (“no specific value”)

    1
    2
    3
    useful when you need to specify something in one of the two fields in which the character is allowed,
    but not the other. For example, if I want my trigger to fire on a particular day of the month (say, the 10th),
    but don’t care what day of the week that happens to be, I would put “10” in the day-of-month field, and “?” in the day-of-week field.

对比这些说明,现在能否理解上面的两个实例?

疑点解析

  • ? 和* 能互换吗
    还是这个例子 0 0 0/1 1/1 * ? *0 0 0/1 1/1 * * * 是等效的吗? 答案是等效的.

0 15 10 * * ? 20050 15 10 * * * 2005 是等效的吗?答案是第二个表达式是错的
不能同时指定一个月的某一天和一周的某一天,所以会有?字符的引入. 也就是这两个字符不能同时出现在表达式里面

使用实战

java 使用 CronExpression 来操作cron expressioni ,这个jar包的api见 link