Quartz.Net系列(九):Trigger之CronScheduleBuilder和Cron表达式详解
1.使用
var scheduler =await StdSchedulerFactory.GetDefaultScheduler(); await scheduler.Start(); var job = JobBuilder.Create<FirstJob>().Build(); var trigger = TriggerBuilder.Create().WithCronSchedule("* * * * * ?").Build(); await scheduler.ScheduleJob(job, trigger);
2.效果图
3.源码解析
public static TriggerBuilder WithCronSchedule(this TriggerBuilder triggerBuilder, string cronExpression)
{
CronScheduleBuilder builder = CronScheduleBuilder.CronSchedule(cronExpression);
return triggerBuilder.WithSchedule(builder);
}
protected virtual int StoreExpressionVals(int pos, string s, int type)
{
int incr = ;
int i = SkipWhiteSpace(pos, s);
if (i >= s.Length)
{
return i;
}
char c = s[i];
if (c >= 'A' && c <= 'Z' && !s.Equals("L") && !s.Equals("LW") && !regex.IsMatch(s))
{
string sub = s.Substring(i, );
int sval;
int eval = -;
if (type == Month)
{
sval = GetMonthNumber(sub) + ;
if (sval <= )
{
throw new FormatException($"Invalid Month value: '{sub}'");
}
if (s.Length > i + )
{
c = s[i + ];
if (c == '-')
{
i += ;
sub = s.Substring(i, );
eval = GetMonthNumber(sub) + ;
if (eval <= )
{
throw new FormatException(
$"Invalid Month value: '{sub}'");
}
}
}
}
else if (type == DayOfWeek)
{
sval = GetDayOfWeekNumber(sub);
if (sval < )
{
throw new FormatException($"Invalid Day-of-Week value: '{sub}'");
}
if (s.Length > i + )
{
c = s[i + ];
if (c == '-')
{
i += ;
sub = s.Substring(i, );
eval = GetDayOfWeekNumber(sub);
if (eval < )
{
throw new FormatException(
$"Invalid Day-of-Week value: '{sub}'");
}
}
else if (c == '#')
{
try
{
i += ;
nthdayOfWeek = Convert.ToInt32(s.Substring(i), CultureInfo.InvariantCulture);
if (nthdayOfWeek < || nthdayOfWeek > )
{
throw new Exception();
}
}
catch (Exception)
{
throw new FormatException(
"A numeric value between 1 and 5 must follow the '#' option");
}
}
else if (c == '/')
{
try
{
i += ;
everyNthWeek = Convert.ToInt32(s.Substring(i), CultureInfo.InvariantCulture);
if (everyNthWeek < || everyNthWeek > )
{
throw new Exception();
}
}
catch (Exception)
{
throw new FormatException(
"A numeric value between 1 and 5 must follow the '/' option");
}
}
else if (c == 'L')
{
lastdayOfWeek = true;
i++;
}
else
{
throw new FormatException($"Illegal characters for this position: '{sub}'");
}
}
}
else
{
throw new FormatException($"Illegal characters for this position: '{sub}'");
}
if (eval != -)
{
incr = ;
}
AddToSet(sval, eval, incr, type);
return i + ;
} if (c == '?')
{
i++;
if (i + < s.Length && s[i] != ' ' && s[i + ] != '\t')
{
throw new FormatException("Illegal character after '?': "
+ s[i]);
}
if (type != DayOfWeek && type != DayOfMonth)
{
throw new FormatException(
"'?' can only be specified for Day-of-Month or Day-of-Week.");
}
if (type == DayOfWeek && !lastdayOfMonth)
{
int val = daysOfMonth.LastOrDefault();
if (val == NoSpecInt)
{
throw new FormatException(
"'?' can only be specified for Day-of-Month -OR- Day-of-Week.");
}
} AddToSet(NoSpecInt, -, , type);
return i;
} var startsWithAsterisk = c == '*';
if (startsWithAsterisk || c == '/')
{
if (startsWithAsterisk && i + >= s.Length)
{
AddToSet(AllSpecInt, -, incr, type);
return i + ;
}
if (c == '/' && (i + >= s.Length || s[i + ] == ' ' || s[i + ] == '\t'))
{
throw new FormatException("'/' must be followed by an integer.");
}
if (startsWithAsterisk)
{
i++;
}
c = s[i];
if (c == '/')
{
// is an increment specified?
i++;
if (i >= s.Length)
{
throw new FormatException("Unexpected end of string.");
} incr = GetNumericValue(s, i); i++;
if (incr > )
{
i++;
}
CheckIncrementRange(incr, type);
}
else
{
if (startsWithAsterisk)
{
// invalid value s
throw new FormatException("Illegal characters after asterisk: " + s);
}
incr = ;
} AddToSet(AllSpecInt, -, incr, type);
return i;
}
if (c == 'L')
{
i++;
if (type == DayOfMonth)
{
lastdayOfMonth = true;
}
if (type == DayOfWeek)
{
AddToSet(, , , type);
}
if (type == DayOfMonth && s.Length > i)
{
c = s[i];
if (c == '-')
{
ValueSet vs = GetValue(, s, i + );
lastdayOffset = vs.theValue;
if (lastdayOffset > )
{
throw new FormatException("Offset from last day must be <= 30");
}
i = vs.pos;
}
if (s.Length > i)
{
c = s[i];
if (c == 'W')
{
nearestWeekday = true;
i++;
}
}
}
return i;
}
if (c >= '' && c <= '')
{
int val = Convert.ToInt32(c.ToString(), CultureInfo.InvariantCulture);
i++;
if (i >= s.Length)
{
AddToSet(val, -, -, type);
}
else
{
c = s[i];
if (c >= '' && c <= '')
{
ValueSet vs = GetValue(val, s, i);
val = vs.theValue;
i = vs.pos;
}
i = CheckNext(i, s, val, type);
return i;
}
}
else
{
throw new FormatException($"Unexpected character: {c}");
} return i;
}
4.Cron表达式详解
Cron表达式是一个字符串,字符串以5或6个空格隔开,分为6或7个域,每一个域代表一个含义,Cron有如下两种语法格式:
(1) Seconds Minutes Hours DayofMonth Month DayofWeek Year
(2)Seconds Minutes Hours DayofMonth Month DayofWeek
一、结构
corn从左到右(用空格隔开):秒 分 小时 月份中的日期 月份 星期中的日期 年份
二、各字段的含义
字段 | 允许值 | 允许的特殊字符 |
秒(Seconds) | 0~59的整数 | , - * / 四个字符 |
分(Minutes) | 0~59的整数 | , - * / 四个字符 |
小时(Hours) | 0~23的整数 | , - * / 四个字符 |
日期(DayofMonth) | 1~31的整数(但是你需要考虑你月的天数) | ,- * ? / L W C 八个字符 |
月份(Month) | 1~12的整数或者 JAN-DEC | , - * / 四个字符 |
星期(DayofWeek) | 1~7的整数或者 SUN-SAT (1=SUN) | , - * ? / L C # 八个字符 |
年(可选,留空)(Year) | 1970~2099 | , - * / 四个字符 |
注意事项:
每一个域都使用数字,但还可以出现如下特殊字符,它们的含义是:
(1)*:表示匹配该域的任意值。假如在Minutes域使用*, 即表示每分钟都会触发事件。
(2)?:只能用在DayofMonth和DayofWeek两个域。它也匹配域的任意值,但实际不会。因为DayofMonth和DayofWeek会相互影响。例如想在每月的20日触发调度,不管20日到底是星期几,则只能使用如下写法: 13 13 15 20 * ?, 其中最后一位只能用?,而不能使用*,如果使用*表示不管星期几都会触发,实际上并不是这样。
(3)-:表示范围。例如在Minutes域使用5-20,表示从5分到20分钟每分钟触发一次
(4)/:表示起始时间开始触发,然后每隔固定时间触发一次。例如在Minutes域使用5/20,则意味着5分钟触发一次,而25,45等分别触发一次.
(5),:表示列出枚举值。例如:在Minutes域使用5,20,则意味着在5和20分每分钟触发一次。
(6)L:表示最后,只能出现在DayofWeek和DayofMonth域。如果在DayofWeek域使用5L,意味着在最后的一个星期四触发。
(7)W:表示有效工作日(周一到周五),只能出现在DayofMonth域,系统将在离指定日期的最近的有效工作日触发事件。例如:在 DayofMonth使用5W,如果5日是星期六,则将在最近的工作日:星期五,即4日触发。如果5日是星期天,则在6日(周一)触发;如果5日在星期一到星期五中的一天,则就在5日触发。另外一点,W的最近寻找不会跨过月份 。
(8)LW:这两个字符可以连用,表示在某个月最后一个工作日,即最后一个星期五。
(9)#:用于确定每个月第几个星期几,只能出现在DayofMonth域。例如在4#2,表示某月的第二个星期三。
三、常用表达式例子
(1)0 0 2 1 * ? * 表示在每月的1日的凌晨2点调整任务
(2)0 15 10 ? * MON-FRI 表示周一到周五每天上午10:15执行作业
(3)0 15 10 ? 6L 2002-2006 表示2002-2006年的每个月的最后一个星期五上午10:15执行作
(4)0 0 10,14,16 * * ? 每天上午10点,下午2点,4点
(5)0 0/30 9-17 * * ? 朝九晚五工作时间内每半小时
(6)0 0 12 ? * WED 表示每个星期三中午12点
(7)0 0 12 * * ? 每天中午12点触发
(8)0 15 10 ? * * 每天上午10:15触发
(9)0 15 10 * * ? 每天上午10:15触发
(10)0 15 10 * * ? * 每天上午10:15触发
(11)0 15 10 * * ? 2005 2005年的每天上午10:15触发
(12)0 * 14 * * ? 在每天下午2点到下午2:59期间的每1分钟触发
(13)0 0/5 14 * * ? 在每天下午2点到下午2:55期间的每5分钟触发
(14)0 0/5 14,18 * * ? 在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发
(15)0 0-5 14 * * ? 在每天下午2点到下午2:05期间的每1分钟触发
(16)0 10,44 14 ? 3 WED 每年三月的星期三的下午2:10和2:44触发
(17)0 15 10 ? * MON-FRI 周一至周五的上午10:15触发
(18)0 15 10 15 * ? 每月15日上午10:15触发
(19)0 15 10 L * ? 每月最后一日的上午10:15触发
(20)0 15 10 ? * 6L 每月的最后一个星期五上午10:15触发
(21)0 15 10 ? * 6L 2002-2005 2002年至2005年的每月的最后一个星期五上午10:15触发
(22)0 15 10 ? * 6#3 每月的第三个星期五上午10:15触发
注:
(1)有些子表达式能包含一些范围或列表
例如:子表达式(天(星期))可以为 “MON-FRI”,“MON,WED,FRI”,“MON-WED,SAT”
“*”字符代表所有可能的值
因此,“*”在子表达式(月)里表示每个月的含义,“*”在子表达式(天(星期))表示星期的每一天
“/”字符用来指定数值的增量
例如:在子表达式(分钟)里的“0/15”表示从第0分钟开始,每15分钟
在子表达式(分钟)里的“3/20”表示从第3分钟开始,每20分钟(它和“3,23,43”)的含义一样
“?”字符仅被用于天(月)和天(星期)两个子表达式,表示不指定值
当2个子表达式其中之一被指定了值以后,为了避免冲突,需要将另一个子表达式的值设为“?”
“L” 字符仅被用于天(月)和天(星期)两个子表达式,它是单词“last”的缩写
但是它在两个子表达式里的含义是不同的。
在天(月)子表达式中,“L”表示一个月的最后一天
在天(星期)自表达式中,“L”表示一个星期的最后一天,也就是SAT
如果在“L”前有具体的内容,它就具有其他的含义了
例如:“6L”表示这个月的倒数第6天,“FRIL”表示这个月的最一个星期五
注意:在使用“L”参数时,不要指定列表或范围,因为这会导致问题
Quartz.Net系列(九):Trigger之CronScheduleBuilder和Cron表达式详解的更多相关文章
- Quartz.net配置文件实例及cron表达式详解
从XML文件创建作业 最新版本的quartz.net支持直接从xml文件创建作业,使用起来很方便.配置文件的格式可以参考下面的例子 <?xml version="1.0" e ...
- quartz.net 时间表达式----- Cron表达式详解
序言 Cron表达式:就是用简单的xxoo符号按照一定的规则,就能把各种时间维度表达的淋漓尽致,无所不在其中,然后在用来做任务调度(定时服务)的quart.net中所认知执行,可想而知这是多么的天衣无 ...
- (2)Spring集成Quartz定时任务框架介绍和Cron表达式详解
在JavaEE系统中,我们会经常用到定时任务,比如每天凌晨生成前天报表,每一小时生成汇总数据等等.我们可以使用java.util.Timer结合java.util.TimerTask来完成这项工作,但 ...
- Spring集成Quartz定时任务框架介绍和Cron表达式详解
原文地址:http://www.cnblogs.com/obullxl/archive/2011/07/10/spring-quartz-cron-integration.html 在JavaEE系统 ...
- quartz定时任务cron表达式详解
引用:https://www.cnblogs.com/lazyInsects/p/8075487.html cron表达式用于配置cronTrigger的实例.cron表达式实际上是由七个子表达式组成 ...
- Spring_Spring集成Quartz定时任务框架介绍和Cron表达式详解
在JavaEE系统中,我们会经常用到定时任务,比如每天凌晨生成前天报表,每一小时生成汇总数据等等.我们可以使用java.util.Timer结合java.util.TimerTask来完成这项工作,但 ...
- Spring之Quartz定时任务和Cron表达式详解
1.定时业务逻辑类 public class ExpireJobTask { /** Logger */ private static final Logger logger = LoggerFact ...
- Quartz Cron表达式详解
转:https://www.jianshu.com/p/f03b1497122a 本文包含如下内容 CronTrigger简介 Cron 表达式 Cron表达式可选的值 Cron表达式的配置规则 Cr ...
- 单元测试系列之十一:Jmockit之mock特性详解
本文是Jmockit学习过程中,根据官网所列的工具特性进行解读. 1.调用次数约束(Invocation count constraints) 可以通过调用计数约束来指定预期和/或允许匹配给定期望的调 ...
随机推荐
- opencl(5)缓存对象
//创建的内存对象由内核访问,将缓冲区作为参数传递给内核 1:创建缓存对象 cl_mem clCreateBuffer( cl_context context, //上下文 cl_mem_flags ...
- .gitignore文件详细说明
简介 有些时候,你必须把某些文件放到 Git 工作目录中,但又不能提交它们,比如保存了数据库密码的配置文件.Java编译生成的.class文件.处理这个需求很简单,从不git add它们就可以.但这样 ...
- 洛谷P1012 拼数 【题解】
**原题链接** 题目描述 设有n个正整数(n ≤ 20),将它们联接成一排,组成一个最大的多位整数. 例如:n=3时,3个整数13,312,343联接成的最大整数为:34331213 又如:n=4时 ...
- Python 字符串、列表和元组用法详解
1.通用函数 len() #列表的元素个数.字符串的长度 2.''' '''与'\ '用法详解 s='''this is a text ''' -->输出s ---> 'this\nis\ ...
- 一个static和面试官扯了一个小时,舌战加强版
一:背景 1. 讲故事 最近也是奇怪,在社区里看到好几篇文章聊static 的玩法以及怎么拿这个和面试官扯半个小时,有点意思,点进去看都是java版的,这就没意思了,怎么也得有一篇和面试官扯C# 中的 ...
- 4.keras-交叉熵的介绍和应用
keras-交叉熵的介绍和应用 1.载入数据以及预处理 import numpy as np from keras.datasets import mnist from keras.utils imp ...
- 06.Django-用户认证
用户认证 Django 内置一个 auth 模块,帮助用户实现注册.登录.注销以及修改密码等功能,帮助开发者省去了很多功夫 用于认证的数据表 auth_user User是auth模块中维护用户信息的 ...
- KMP 知识点整理
1.扩展KMP 2.最大表示法 3.最小表示法 (扩展KMP) hdu2594 模板题 #include <iostream> #include <cstdio> #incl ...
- Mini Linux的制作过程
- java处理csv文件上传示例
前言:示例只是做了一个最最基础的上传csv的示例,如果要引用到代码中去,还需要根据自己的业务自行添加一些逻辑处理. ReadCsvUtil工具类 package com.hanfengyeqiao.g ...