quartz时间表达式Cron详解

cron的表达式被用来配置CronTrigger实例。

cron的表达式是字符串,实际上是由七子表达式,描述个别细节的时间表。

这些子表达式是分开的空白,代表:

Seconds Minutes Hours Day-of-Month Month Day-of-Week Year (可选字段)

例? “0 0 12 ? * WED” 在每星期三下午12:00 执行,个别子表达式可以包含范围;

例如,在前面的例子里(“WED”)可以替换成 “MON-FRI”, “MON, WED, FRI”甚至”MON-WED,SAT”.“*” 代表整个时间段.

每一个字段都有一套可以指定有效值,如

Seconds (秒)         :可以用数字0-59 表示,Minutes(分)          :可以用数字0-59 表示,Hours(时)            :可以用数字0-23表示,Day-of-Month(天)    :可以用数字1-31 中的任一一个值,但要注意一些特别的月份Month(月)            :可以用0-11 或用字符串  “JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV and DEC” 表示Day-of-Week(每周)   :可以用数字1-7表示(1 = 星期日)或用字符口串“SUN, MON, TUE, WED, THU, FRI and SAT”表示 “*”:指定所有的值,比如,Minutes 设置为 *,表示每分钟? “/”:为特别单位,表示为“每”如“0/15”表示每隔15分钟执行一次,“0”表示为从“0”分开始, “3/20”表示表示每隔20分钟执行一次,“3”表示从第3分钟开始执行 “?”:表示每月的某一天,或第周的某一天 “L”:用于每月,或每周,表示为每月的最后一天,或每个月的最后星期几如“6L”表示“每月的最后一个星期五” “W”:表示为最近工作日,如“15W”放在每月(day-of-month)字段上表示为“到本月15日最近的工作日” “#”:是用来指定“的”每月第n个工作日,例 在每周(day-of-week)这个字段中内容为"6#3" or "FRI#3" 则表示“每月第三个星期五”

注意:? Day-of-Month 和 Day-of-Week不可同时为 * ,否则报错:

 java.lang.RuntimeException: CronExpression '0/2 * * * * * *' is invalid.      at org.quartz.CronScheduleBuilder.cronSchedule(CronScheduleBuilder.java:111)     at quartz.QuartzExample.getTrigger(QuartzExample.java:110)     at quartz.QuartzExample.run(QuartzExample.java:74)     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)     at java.lang.reflect.Method.invoke(Method.java:606)     at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)     at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)     at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)     at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)     at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)     at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)     at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)     at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)     at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)     at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)     at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)     at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)     at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)     at org.junit.runners.ParentRunner.run(ParentRunner.java:363)     at org.junit.runner.JUnitCore.run(JUnitCore.java:137)     at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)     at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)     at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)     at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) Caused by: java.text.ParseException: Support for specifying both a day-of-week AND a day-of-month parameter is not implemented.     at org.quartz.CronExpression.buildExpression(CronExpression.java:511)     at org.quartz.CronExpression.<init>(CronExpression.java:276)     at org.quartz.CronScheduleBuilder.cronSchedule(CronScheduleBuilder.java:107)     ... 25 more  Disconnected from the target VM, address: '127.0.0.1:61437', transport: 'socket'  Process finished with exit code -1

CronExpression 源码:

protected void buildExpression(String expression) throws ParseException {        expressionParsed = true;        try {            if (seconds == null) {                seconds = new TreeSet<Integer>();            }            if (minutes == null) {                minutes = new TreeSet<Integer>();            }            if (hours == null) {                hours = new TreeSet<Integer>();            }            if (daysOfMonth == null) {                daysOfMonth = new TreeSet<Integer>();            }            if (months == null) {                months = new TreeSet<Integer>();            }            if (daysOfWeek == null) {                daysOfWeek = new TreeSet<Integer>();            }            if (years == null) {                years = new TreeSet<Integer>();            }            int exprOn = SECOND;            StringTokenizer exprsTok = new StringTokenizer(expression, " \t",                    false);            while (exprsTok.hasMoreTokens() && exprOn <= YEAR) {                String expr = exprsTok.nextToken().trim();                // throw an exception if L is used with other days of the month                if(exprOn == DAY_OF_MONTH && expr.indexOf('L') != -1 && expr.length() > 1 && expr.contains(",")) {                    throw new ParseException("Support for specifying 'L' and 'LW' with other days of the month is not implemented", -1);                }                // throw an exception if L is used with other days of the week                if(exprOn == DAY_OF_WEEK && expr.indexOf('L') != -1 && expr.length() > 1  && expr.contains(",")) {                    throw new ParseException("Support for specifying 'L' with other days of the week is not implemented", -1);                }                if(exprOn == DAY_OF_WEEK && expr.indexOf('#') != -1 && expr.indexOf('#', expr.indexOf('#') +1) != -1) {                    throw new ParseException("Support for specifying multiple \"nth\" days is not implemented.", -1);                }                                StringTokenizer vTok = new StringTokenizer(expr, ",");                while (vTok.hasMoreTokens()) {                    String v = vTok.nextToken();                    storeExpressionVals(0, v, exprOn);                }                exprOn++;            }            if (exprOn <= DAY_OF_WEEK) {                throw new ParseException("Unexpected end of expression.",                            expression.length());            }            if (exprOn <= YEAR) {                storeExpressionVals(0, "*", YEAR);            }            TreeSet<Integer> dow = getSet(DAY_OF_WEEK);            TreeSet<Integer> dom = getSet(DAY_OF_MONTH);            // Copying the logic from the UnsupportedOperationException below            boolean dayOfMSpec = !dom.contains(NO_SPEC);            boolean dayOfWSpec = !dow.contains(NO_SPEC);            if (!dayOfMSpec || dayOfWSpec) {                if (!dayOfWSpec || dayOfMSpec) {                    throw new ParseException(                            "Support for specifying both a day-of-week AND a day-of-month parameter is not implemented.", 0);                }            }        } catch (ParseException pe) {            throw pe;        } catch (Exception e) {            throw new ParseException("Illegal cron expression format ("                    + e.toString() + ")", 0);        }    }CronExpression 部分代码

1)Cron表达式的格式:

秒 分 时 日 月 周 年(可选)。

字段名 允许的值 允许的特殊字符 秒 0-59 , – * / 分 0-59 , – * / 小时 0-23 , – * / 日 1-31 , – * ? / L W C 月 1-12 or JAN-DEC , – * / 周几 1-7 or SUN-SAT , – * ? / L C # 年(可选字段) empty, 1970-2099 , – * /

“?”字符:表示不确定的值 “,”字符:指定数个值 “-”字符:指定一个值的范围 “/”字符:指定一个值的增加幅度。n/m表示从n开始,每次增加m “L”字符:用在日表示一个月中的最后一天,用在周表示该月最后一个星期X “W”字符:指定离给定日期最近的工作日(周一到周五) “#”字符:表示该月第几个周X。6#3表示该月第3个周五2)Cron表达式范例:

每隔5秒执行一次:*/5 * * * * ? 每隔1分钟执行一次:0 */1 * * * ? 每天23点执行一次:0 0 23 * * ? 每天凌晨1点执行一次:0 0 1 * * ? 每月1号凌晨1点执行一次:0 0 1 1 * ? 每月最后一天23点执行一次:0 0 23 L * ? 每周星期天凌晨1点实行一次:0 0 1 ? * L 在26分、29分、33分执行一次:0 26,29,33 * * * ? 每天的0点、13点、18点、21点都执行一次:0 0 0,13,18,21 * * ? 每天的7点到21点都执行一次:0 0 7-21 * * ?

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

旅行,有一种苍凉,“浮云游子意,落日故人情”,

quartz时间表达式Cron详解

相关文章:

你感兴趣的文章:

标签云: