Can't remember the cron syntax in scheduled in spring? Let's take a look at the source code

Strategy 2020-11-06 20:59:01
remember cron syntax scheduled spring


stay Spring Source code , analysis cron The source code of is located in CronExpression in , When creating timed tasks , Called CornExpression.parse Methods to do analysis

public CronTrigger(String expression, ZoneId zoneId) {
Assert.hasLength(expression, "Expression must not be empty");
Assert.notNull(zoneId, "ZoneId must not be null");
this.expression = CronExpression.parse(expression);
this.zoneId = zoneId;
}

Now let's uncover the resolution cron The mysterious veil of expression

public static CronExpression parse(String expression) {
Assert.hasLength(expression, "Expression string must not be empty");
// If expression It's in the form of annotations , Replace the annotation with the following form ( See tail )
expression = resolveMacros(expression);
// StringUtils.tokenizeToStringArray And split The function of the method is similar 
String[] fields = StringUtils.tokenizeToStringArray(expression, " ");
if (fields.length != 6) {
// cron The expression must consist of six terms 
throw new IllegalArgumentException(String.format(
"Cron expression must consist of 6 fields (found %d in \"%s\")", fields.length, expression));
}
try {
CronField seconds = CronField.parseSeconds(fields[0]); // The first one is seconds 
CronField minutes = CronField.parseMinutes(fields[1]); // The second one is the score 
CronField hours = CronField.parseHours(fields[2]); // The third is when 
CronField daysOfMonth = CronField.parseDaysOfMonth(fields[3]); // The fourth item is Japanese 
CronField months = CronField.parseMonth(fields[4]); // The fifth is the month 
CronField daysOfWeek = CronField.parseDaysOfWeek(fields[5]); // The sixth is the year 
return new CronExpression(seconds, minutes, hours, daysOfMonth, months, daysOfWeek, expression);
}
catch (IllegalArgumentException ex) {
String msg = ex.getMessage() + " in cron expression \"" + expression + "\"";
throw new IllegalArgumentException(msg, ex);
}
}
// resolveMacros function 
private static String resolveMacros(String expression) {
expression = expression.trim();
for (int i = 0; i < MACROS.length; i = i + 2) {
if (MACROS[i].equalsIgnoreCase(expression)) {
return MACROS[i + 1];
}
}
return expression;
}
private static final String[] MACROS = new String[] {
"@yearly", "0 0 0 1 1 *",
"@annually", "0 0 0 1 1 *",
"@monthly", "0 0 0 1 * *",
"@weekly", "0 0 0 * * 0",
"@daily", "0 0 0 * * *",
"@midnight", "0 0 0 * * *",
"@hourly", "0 0 * * * *"
};

Now? ,cron The order of expressions we remember , It has to be six , The order is second , branch , when , Japan , month , Year or as defined in the system MACROS Instead of , The six items are separated by spaces . So how is each item interpreted and expressed ? Let's see CronField Related definitions in .

// second 
public static CronField parseSeconds(String value) {
return BitsCronField.parseSeconds(value);
}
// This call stack is just like the dolls 
public static BitsCronField parseSeconds(String value) {
return parseField(value, Type.SECOND);
}
private static BitsCronField parseField(String value, Type type) {
Assert.hasLength(value, "Value must not be empty");
Assert.notNull(type, "Type must not be null");
try {
BitsCronField result = new BitsCronField(type);
// Separate strings by commas , That is to say , We can use commas to separate each item , For different times 
String[] fields = StringUtils.delimitedListToStringArray(value, ",");
for (String field : fields) {
int slashPos = field.indexOf('/');
// Judge whether there is a slash in the time 
if (slashPos == -1) {
// without , Just parse and set the time range 
ValueRange range = parseRange(field, type);
result.setBits(range);
}
else {
String rangeStr = value.substring(0, slashPos);
String deltaStr = value.substring(slashPos + 1);
// Parse and create a time range based on the content before the slash 
ValueRange range = parseRange(rangeStr, type);
if (rangeStr.indexOf('-') == -1) {
// If the expression before the slash does not contain a horizontal bar , Will be the current range The end time of is set to the maximum value of the current type 
range = ValueRange.of(range.getMinimum(), type.range().getMaximum());
}
int delta = Integer.parseInt(deltaStr);
if (delta <= 0) {
throw new IllegalArgumentException("Incrementer delta must be 1 or higher");
}
// take delta Bring it in and set the time range 
result.setBits(range, delta);
}
}
return result;
}
catch (DateTimeException | IllegalArgumentException ex) {
String msg = ex.getMessage() + " '" + value + "'";
throw new IllegalArgumentException(msg, ex);
}
}
// parseRange
private static ValueRange parseRange(String value, Type type) {
if (value.equals("*")) {
// If it is * Number , Of this type range()
return type.range();
}
else {
int hyphenPos = value.indexOf('-');
if (hyphenPos == -1) {
int result = type.checkValidValue(Integer.parseInt(value));
// If there is no horizontal bar , Then the beginning and end of the time period are the current event points 
return ValueRange.of(result, result);
}
else {
// If there are bars , So the beginning of the time period is the number before the bar , The end is the number after the bar 
int min = Integer.parseInt(value.substring(0, hyphenPos));
int max = Integer.parseInt(value.substring(hyphenPos + 1));
min = type.checkValidValue(min); // check 
max = type.checkValidValue(max); // check 
return ValueRange.of(min, max);
}
}
}
// setBits Method ,BitsCronField Use a long integer in the implementation bits To store a bit of time 
private void setBits(ValueRange range) {
// without delta
if (range.getMinimum() == range.getMaximum()) {
// If it's a point in time , Because of our bits The default value of is 0, So the semantics here is to directly put bits Of the range.getMinimum() position , Set as 1
setBit((int) range.getMinimum());
}
else {
// If it's a time period , Will Mask Move left range.getMinimum() The value of bit is set to minMask
// take Mask unsigned right shift - (range.getMaximum() + 1) position 
// private static final long MASK = 0xFFFFFFFFFFFFFFFFL;
// This is very complicated to avoid the problem of right shift overflow , But it's also in essence bits Of range.getMinimum() and range.getMaximum() position , Set as 1
long minMask = MASK << range.getMinimum();
long maxMask = MASK >>> - (range.getMaximum() + 1);
this.bits |= (minMask & maxMask);
}
}
// Call this method when there is a slash 
private void setBits(ValueRange range, int delta) {
if (delta == 1) {
// If there is delta, And for 1, It's no different from No 
setBits(range);
}
else {
// If delta Not for 1, According to delta Set the position for the tolerance 1
for (int i = (int) range.getMinimum(); i <= range.getMaximum(); i += delta) {
setBit(i);
}
}
}
// Get current bits And (1L << index) The result of bitwise OR , Press bit or just There is one 
// We know , Basic types have default values ,long The default value of type is 0
// for example , If it's a point in time , Because of our bits The default value of is 0, So the semantics here is to directly put bits Of the range.getMinimum() The position is 1
private void setBit(int index) {
this.bits |= (1L << index);
}

It just called type.range Method , According to the call stack , It will come ChronoField Enumerating , in other words , If it's an asterisk , It returns the entire event scope of the current parse type . From here we can see that , The asterisk represents all times of all current resolution types , If there is a bar in the expression , So it represents a period of time , If it's a pure number , So that's the time point .

public enum ChronoField implements TemporalField {
NANO_OF_SECOND("NanoOfSecond", NANOS, SECONDS, ValueRange.of(0, 999_999_999)),
NANO_OF_DAY("NanoOfDay", NANOS, DAYS, ValueRange.of(0, 86400L * 1000_000_000L - 1)),
MICRO_OF_SECOND("MicroOfSecond", MICROS, SECONDS, ValueRange.of(0, 999_999)),
MICRO_OF_DAY("MicroOfDay", MICROS, DAYS, ValueRange.of(0, 86400L * 1000_000L - 1)),
MILLI_OF_SECOND("MilliOfSecond", MILLIS, SECONDS, ValueRange.of(0, 999)),
MILLI_OF_DAY("MilliOfDay", MILLIS, DAYS, ValueRange.of(0, 86400L * 1000L - 1)),
SECOND_OF_MINUTE("SecondOfMinute", SECONDS, MINUTES, ValueRange.of(0, 59), "second"),
SECOND_OF_DAY("SecondOfDay", SECONDS, DAYS, ValueRange.of(0, 86400L - 1)),
MINUTE_OF_HOUR("MinuteOfHour", MINUTES, HOURS, ValueRange.of(0, 59), "minute"),
MINUTE_OF_DAY("MinuteOfDay", MINUTES, DAYS, ValueRange.of(0, (24 * 60) - 1)),
HOUR_OF_AMPM("HourOfAmPm", HOURS, HALF_DAYS, ValueRange.of(0, 11)),
CLOCK_HOUR_OF_AMPM("ClockHourOfAmPm", HOURS, HALF_DAYS, ValueRange.of(1, 12)),
HOUR_OF_DAY("HourOfDay", HOURS, DAYS, ValueRange.of(0, 23), "hour"),
CLOCK_HOUR_OF_DAY("ClockHourOfDay", HOURS, DAYS, ValueRange.of(1, 24)),
AMPM_OF_DAY("AmPmOfDay", HALF_DAYS, DAYS, ValueRange.of(0, 1), "dayperiod"),
DAY_OF_WEEK("DayOfWeek", DAYS, WEEKS, ValueRange.of(1, 7), "weekday"),
ALIGNED_DAY_OF_WEEK_IN_MONTH("AlignedDayOfWeekInMonth", DAYS, WEEKS, ValueRange.of(1, 7)),
ALIGNED_DAY_OF_WEEK_IN_YEAR("AlignedDayOfWeekInYear", DAYS, WEEKS, ValueRange.of(1, 7)),
DAY_OF_MONTH("DayOfMonth", DAYS, MONTHS, ValueRange.of(1, 28, 31), "day"),
DAY_OF_YEAR("DayOfYear", DAYS, YEARS, ValueRange.of(1, 365, 366)),
EPOCH_DAY("EpochDay", DAYS, FOREVER, ValueRange.of((long) (Year.MIN_VALUE * 365.25), (long) (Year.MAX_VALUE * 365.25))),
ALIGNED_WEEK_OF_MONTH("AlignedWeekOfMonth", WEEKS, MONTHS, ValueRange.of(1, 4, 5)),
ALIGNED_WEEK_OF_YEAR("AlignedWeekOfYear", WEEKS, YEARS, ValueRange.of(1, 53)),
MONTH_OF_YEAR("MonthOfYear", MONTHS, YEARS, ValueRange.of(1, 12), "month"),
PROLEPTIC_MONTH("ProlepticMonth", MONTHS, FOREVER, ValueRange.of(Year.MIN_VALUE * 12L, Year.MAX_VALUE * 12L + 11)),
YEAR_OF_ERA("YearOfEra", YEARS, FOREVER, ValueRange.of(1, Year.MAX_VALUE, Year.MAX_VALUE + 1)),
YEAR("Year", YEARS, FOREVER, ValueRange.of(Year.MIN_VALUE, Year.MAX_VALUE), "year"),
ERA("Era", ERAS, FOREVER, ValueRange.of(0, 1), "era"),
INSTANT_SECONDS("InstantSeconds", SECONDS, FOREVER, ValueRange.of(Long.MIN_VALUE, Long.MAX_VALUE)),
OFFSET_SECONDS("OffsetSeconds", SECONDS, FOREVER, ValueRange.of(-18 * 3600, 18 * 3600));
private final String name;
private final TemporalUnit baseUnit;
private final TemporalUnit rangeUnit;
private final ValueRange range;
private final String displayNameKey;
private ChronoField(String name, TemporalUnit baseUnit, TemporalUnit rangeUnit, ValueRange range) {
this.name = name;
this.baseUnit = baseUnit;
this.rangeUnit = rangeUnit;
this.range = range;
this.displayNameKey = null;
}
private ChronoField(String name, TemporalUnit baseUnit, TemporalUnit rangeUnit,
ValueRange range, String displayNameKey) {
this.name = name;
this.baseUnit = baseUnit;
this.rangeUnit = rangeUnit;
this.range = range;
this.displayNameKey = displayNameKey;
}
// ... ...
@Override
public ValueRange range() {
return range;
}
// ... ...
}

Get the rules

From the above source code analysis , We can sum up this set of cron Expression parsing rules

1、cron Expressions can be second branch when Japan month year Six part registration , Each part is separated by a space . The system defines a set of @ Start with a string instead of the standard Cron expression , But the number is limited

private static final String[] MACROS = new String[] {
"@yearly", "0 0 0 1 1 *",
"@annually", "0 0 0 1 1 *",
"@monthly", "0 0 0 1 * *",
"@weekly", "0 0 0 * * 0",
"@daily", "0 0 0 * * *",
"@midnight", "0 0 0 * * *",
"@hourly", "0 0 * * * *"
};

for example :

@Scheduled(cron = "@yearly")
public void test(){
logger.info("123");
}

2、 For each item , Can be separated by commas , Used to indicate different time points

for example :

@Scheduled(cron = "1,2,3 0 0 * * *")
public void test(){
logger.info("123");
}

3、 For each item , You can use bars to separate , Used to indicate a period of time

for example :

@Scheduled(cron = "1,2-4,5 0 0 * * *")
public void test(){
logger.info("123");
}

4、 For each item , You can use slashes + Combination of horizontal bars , During this period of time , Take the value after the slash as the time point of tolerance

for example :

@Scheduled(cron = "1,2-20/3,5 0 0 * * *")
public void test(){
logger.info("123");
}

5、 For each item , Use an asterisk to indicate the entire range of the current time type

for example :

@Scheduled(cron = "1,2-20/3,5 * * * * *")
public void test(){
logger.info("123");
}

Fried chicken spicy chicken original article , Please quote source for reprint

版权声明
本文为[Strategy]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云