依赖

cron-utils的github地址:https://github.com/jmrozanec/cron-utils

<dependency>
<groupId>com.cronutils</groupId>
<artifactId>cron-utils</artifactId>
<version>9.2.1</version>
</dependency>

基本使用

定义cron表达式的支持范围

// 创建cron定义,自定义cron表达式支持的范围
CronDefinition cronDefinition =
CronDefinitionBuilder.defineCron()
.withSeconds().and()
.withMinutes().and()
.withHours().and()
.withDayOfMonth()
.supportsHash().supportsL().supportsW().and()
.withMonth().and()
.withDayOfWeek()
.withIntMapping(7, 0)
.supportsHash().supportsL().supportsW().and()
.withYear().optional().and()
.instance(); // 传入要生成的cron表达式类型获取cron定义
cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ);

支持定时任务的类型:

  1. CRON4J
  2. QUARTZ
  3. UNIX
  4. SPRING
  5. SPRING53

生成cron表达式

import static com.cronutils.model.field.expression.FieldExpressionFactory.*;

Cron cron = CronBuilder.cron(CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ))
.withYear(always())
.withDoM(between(SpecialChar.L, 3))
.withMonth(always())
.withDoW(questionMark())
.withHour(always())
.withMinute(always())
.withSecond(on(0))
.instance(); String cronAsString = cron.asString(); // 0 * * L-3 * ? *

各方法对应cron表达式关系:

  1. always:表示*
  2. questionMark:表示?
  3. on:表示具体值
  4. between:表示-,例如,between(0,5)表示0-5
  5. and:表示,,例如,and(on(1),on(5))表示0,5
  6. every:表示/,例如,every(on(2),3)表示2/3

获取cron表达式描述

public class Test {

    public static void main(String[] args) {
// 创建cron描述器
CronDescriptor descriptor = CronDescriptor.instance();
// 创建cron定义
CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(QUARTZ);
// 创建cron解析器
CronParser cronParser = new CronParser(cronDefinition);
String describe = descriptor.describe(cronParser.parse("0 0 12 ? * 6"));
System.out.println(describe);
describe = descriptor.describe(cronParser.parse("*/45 * * * * ?"));
System.out.println(describe); // 设置语言
descriptor = CronDescriptor.instance(Locale.CHINESE);
describe = descriptor.describe(cronParser.parse("0 0 12 ? * 6"));
System.out.println(describe);
describe = descriptor.describe(cronParser.parse("*/45 * * * * ?"));
System.out.println(describe);
}
}
// 运行结果:
at 12:00 at Friday day
every 45 seconds
在 12:00 在 星期五 天
每 45 秒

校验cron表达式的正确性

public class Test {

    public static void main(String[] args) {
CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(QUARTZ);
CronParser cronParser = new CronParser(cronDefinition);
Cron cron = cronParser.parse("0 0 12 ? * 6");
// 校验cron表达式
cron.validate();
cron = cronParser.parse("0 0 12 ? * ?");
cron.validate();
}
}

工具类

WeekEnum

定义星期的枚举类信息

@Getter
@AllArgsConstructor
public enum WeekEnum { SUNDAY(1, "星期天"),
MONDAY(2, "星期一"),
TUESDAY(3, "星期二"),
WEDNESDAY(4, "星期三"),
THURSDAY(5, "星期四"),
FRIDAY(6, "星期五"),
SATURDAY(7, "星期六"); private Integer code; private String desc;
}

CycleTypeEnum

定义要生成的cron表达式类型枚举类信息

@Getter
@AllArgsConstructor
public enum CycleTypeEnum { MINUTE(1, "分钟"),
HOUR(2, "小时"),
DAY(3, "日"),
WEEK(4, "周"),
MONTH(5, "月"),
QUARTER(6, "季度"),
YEAR(7, "年"); private Integer code; private String desc;
}

RepeatRuleEnum

定义要生成月、季度的cron表达式循环规则枚举类信息

@Getter
@AllArgsConstructor
public enum RepeatRuleEnum { WEEK(1, "周"),
DATE(2, "日期"); private Integer code; private String desc;
}

CronDto

定义cron表达式工具类的请求体信息

@Data
public class CronDto { /**
* 周期类型 minute:分钟 hour: 小时; day: 天; week: 周; month: 月; quarter: 季; year: 年
*/
private Integer cycleType; /**
* 执行时间
*/
private LocalDateTime executionTime; /**
* 指定一周哪几天
*/
private List<Integer> weekDays; /**
* 指定一个月哪几天
*/
private List<Integer> monthDays; /**
* 指定一年哪几月
*/
private List<Integer> quartzMonths; /**
* 一周的星期几
*/
private Integer dayOfWeek; /**
* 第几周
*/
private Integer week; /**
* 重复规则:周 天
*/
private Integer repeatRule;
}

CronUtils

根据年、月、日、时、分、秒、星期、季度实现不同的cron表达式

注意:生成年、月、季度的cron表达式时可以根据日或者星期额外判断

public class CronUtils {

    /**
* 星期
*/
private static final List<Integer> WEEKS = Arrays.stream(WeekEnum.values()).map(WeekEnum::getCode).collect(Collectors.toList()); public static String createCron(CronDto cronDto) {
Integer cycleType = cronDto.getCycleType();
LocalDateTime executionTime = cronDto.getExecutionTime();
CronBuilder cronBuilder = CronBuilder.cron(CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ));
// 每分钟一次
if (Objects.equals(CycleTypeEnum.MINUTE.getCode(), cycleType)) {
return getSecondCron(cronBuilder, executionTime);
}
// 每小时一次
if (Objects.equals(CycleTypeEnum.HOUR.getCode(), cycleType)) {
return getMinuteCron(cronBuilder, executionTime);
}
// 每日一次
if (Objects.equals(CycleTypeEnum.DAY.getCode(), cycleType)) {
return getDayCron(cronBuilder, executionTime);
}
// 每周一次
if (Objects.equals(CycleTypeEnum.WEEK.getCode(), cycleType)) {
return getWeekCron(cronDto, cronBuilder, executionTime);
}
// 每月一次
if (Objects.equals(CycleTypeEnum.MONTH.getCode(), cycleType)) {
return getMonthCron(cronDto, cronBuilder, executionTime);
}
// 每季度一次
if (Objects.equals(CycleTypeEnum.QUARTER.getCode(), cycleType)) {
return getQuarterCron(cronDto, cronBuilder, executionTime);
}
// 每年一次
if (Objects.equals(CycleTypeEnum.YEAR.getCode(), cycleType)) {
return getYearCron(cronBuilder, executionTime);
}
return "";
} public static String getYearCron(CronBuilder cronBuilder, LocalDateTime executionTime) {
return cronBuilder.withSecond(on(executionTime.getSecond()))
.withMinute(on(executionTime.getMinute()))
.withHour(on(executionTime.getHour()))
.withDoM(on(executionTime.getDayOfMonth()))
.withMonth(on(executionTime.getMonthValue()))
.withDoW(questionMark())
.instance()
.asString();
} public static String getQuarterCron(CronDto cronDto, CronBuilder cronBuilder, LocalDateTime executionTime) {
List<FieldExpression> flist = new ArrayList<>();
cronDto.getQuartzMonths().forEach(e -> flist.add(FieldExpressionFactory.on(e)));
return cronBuilder.withSecond(on(executionTime.getSecond()))
.withMinute(on(executionTime.getMinute()))
.withHour(on(executionTime.getHour()))
.withDoM(questionMark())
.withMonth(and(flist))
.withDoW(on(WEEKS.get(cronDto.getDayOfWeek()), SpecialChar.HASH, cronDto.getWeek()))
.instance()
.asString();
} public static String getMonthCron(CronDto cronDto, CronBuilder cronBuilder, LocalDateTime executionTime) {
Integer repeatRule = cronDto.getRepeatRule();
// 按周
if (Objects.equals(RepeatRuleEnum.WEEK.getCode(), repeatRule)) {
List<FieldExpression> weekDays = new ArrayList<>();
if (!CollectionUtils.isEmpty(cronDto.getWeekDays())) {
cronDto.getWeekDays().forEach(e -> weekDays.add(FieldExpressionFactory.on(WEEKS.get(cronDto.getDayOfWeek()),
SpecialChar.HASH, e)));
}
return cronBuilder.withSecond(on(executionTime.getSecond()))
.withMinute(on(executionTime.getMinute()))
.withHour(on(executionTime.getHour()))
.withDoM(questionMark())
.withMonth(always())
.withDoW(CollectionUtils.isEmpty(weekDays) ? on(WEEKS.get(cronDto.getDayOfWeek()), SpecialChar.HASH,
cronDto.getWeek()) : and(weekDays))
.instance()
.asString(); }
// 按天
if (Objects.equals(RepeatRuleEnum.DATE.getCode(), repeatRule)) {
List<FieldExpression> monthDays = new ArrayList<>();
cronDto.getMonthDays().forEach(e -> monthDays.add(FieldExpressionFactory.on(e)));
return cronBuilder.withSecond(on(executionTime.getSecond()))
.withMinute(on(executionTime.getMinute()))
.withHour(on(executionTime.getHour()))
.withDoM(and(monthDays))
.withMonth(always())
.withDoW(questionMark())
.instance()
.asString();
}
return "";
} public static String getWeekCron(CronDto cronDto, CronBuilder cronBuilder, LocalDateTime executionTime) {
List<FieldExpression> weekDays = new ArrayList<>();
cronDto.getWeekDays().forEach(e -> weekDays.add(FieldExpressionFactory.on(e)));
return cronBuilder.withSecond(on(executionTime.getSecond()))
.withMinute(on(executionTime.getMinute()))
.withHour(on(executionTime.getHour()))
.withDoM(questionMark())
.withMonth(always())
.withDoW(and(weekDays))
.instance()
.asString();
} public static String getDayCron(CronBuilder cronBuilder, LocalDateTime executionTime) {
return cronBuilder.withSecond(on(executionTime.getSecond()))
.withMinute(on(executionTime.getMinute()))
.withHour(on(executionTime.getHour()))
.withDoM(always())
.withMonth(always())
.withDoW(questionMark())
.instance()
.asString();
} public static String getMinuteCron(CronBuilder cronBuilder, LocalDateTime executionTime) {
return cronBuilder.withSecond(on(executionTime.getSecond()))
.withMinute(on(executionTime.getMinute()))
.withHour(always())
.withDoM(always())
.withMonth(always())
.withDoW(questionMark())
.instance()
.asString();
} public static String getSecondCron(CronBuilder cronBuilder, LocalDateTime executionTime) {
return cronBuilder.withSecond(on(executionTime.getSecond()))
.withMinute(always())
.withHour(always())
.withDoM(always())
.withMonth(always())
.withDoW(questionMark())
.instance()
.asString();
}
}

使用案例

public class Test {
public static void main(String[] args) {
CronDto cronDto = new CronDto();
cronDto.setCycleType(1);
cronDto.setExecutionTime(LocalDateTime.now());
String cron = createCron(cronDto);
System.out.println(cron); cronDto.setCycleType(2);
cron = createCron(cronDto);
System.out.println(cron); cronDto.setCycleType(3);
cron = createCron(cronDto);
System.out.println(cron); cronDto.setCycleType(4);
cronDto.setWeekDays(Arrays.asList(1, 2));
cron = createCron(cronDto);
System.out.println(cron); cronDto.setCycleType(5);
cronDto.setRepeatRule(1);
cronDto.setDayOfWeek(1);
cron = createCron(cronDto);
System.out.println(cron); cronDto.setCycleType(5);
cronDto.setRepeatRule(1);
cronDto.setWeek(1);
cronDto.setDayOfWeek(1);
cronDto.setWeekDays(null);
cron = createCron(cronDto);
System.out.println(cron); cronDto.setCycleType(5);
cronDto.setRepeatRule(2);
cronDto.setMonthDays(Arrays.asList(1, 2));
cron = createCron(cronDto);
System.out.println(cron); cronDto.setCycleType(6);
cronDto.setQuartzMonths(Arrays.asList(1, 2));
cron = createCron(cronDto);
System.out.println(cron); cronDto.setCycleType(7);
cron = createCron(cronDto);
System.out.println(cron);
}
}
// 运行结果:
14 * * * * ?
14 28 * * * ?
14 28 9 * * ?
14 28 9 ? * 1,2
14 28 9 ? * 2#1,2#2
14 28 9 ? * 2#1
14 28 9 1,2 * ?
14 28 9 ? 1,2 2#1
14 28 9 19 11 ?

定时任务Cron表达式工具类Cron Util的更多相关文章

  1. Thymeleaf 表达式工具类

    Thymeleaf默认提供了丰富的表达式工具类,这里列举一些常用的工具类. Objects工具类 1 2 3 4 5 6 7 8 /* * 当obj不为空时,返回obj,否则返回default默认值 ...

  2. JavaSE-基础语法(二)-系统类(java.lang.*)和工具类(java.util.*)

    系统类(java.lang.*)和工具类(java.util.*) 一.系统类(java.lang.*) 这个包下包含java语言的核心类,如String.Math.System和Thread类等,使 ...

  3. vue项目工具文件utils.js javascript常用工具类,javascript常用工具类,util.js

    vue项目工具文件utils.js :https://blog.csdn.net/Ajaxguan/article/details/79924249 javascript常用工具类,util.js : ...

  4. 百度地图LV1.5实践项目开发工具类bmap.util.jsV1.0

    /** * 百度地图使用工具类-v1.5 * * @author boonya * @date 2013-7-7 * @address Chengdu,Sichuan,China * @email b ...

  5. 转载及总结:cron表达式详解,cron表达式写法,cron表达式例子

    cron表达式格式:{秒数} {分钟} {小时} {日期} {月份} {星期} {年份(可为空)}例  "0 0 12 ? * WED" 在每星期三下午12:00 执行(年份通常 ...

  6. 005-guava 集合-集合工具类-java.util.Collections中未包含的集合工具[Maps,Lists,Sets],Iterables、Multisets、Multimaps、Tables

    一.概述 工具类与特定集合接口的对应关系归纳如下: 集合接口 属于JDK还是Guava 对应的Guava工具类 Collection JDK Collections2:不要和java.util.Col ...

  7. cron表达式详解,cron表达式写法,cron表达式例子

    (cron = "* * * * * *") cron表达式格式:{秒数} {分钟} {小时} {日期} {月份} {星期} {年份(可为空)}例  "0 0 12 ? ...

  8. 百度地图LV1.5实践项目开发工具类bmap.util.jsV1.3

    /** * 百度地图使用工具类-v1.5 * * @author boonya * @date 2013-7-7 * @address Chengdu,Sichuan,China * @email b ...

  9. 百度地图LV1.5实践项目开发工具类bmap.util.jsV1.2

    /** * 百度地图使用工具类-v1.5 * * @author boonya * @date 2013-7-7 * @address Chengdu,Sichuan,China * @email b ...

  10. 百度地图LV1.5实践项目开发工具类bmap.util.jsV1.1

    /** * 百度地图使用工具类-v1.5 * * @author boonya * @date 2013-7-7 * @address Chengdu,Sichuan,China * @email b ...

随机推荐

  1. AI编程:Coze + Cursor实现一个思维导图的浏览器插件

    这是小卷对AI编程工具学习的第3篇文章,今天以实际开发一个思维导图的需求为例,了解AI编程开发的整个过程 1.效果展示 2.AI编程开发流程 虽然AI编程知识简单对话就行,不过咱要逐步深入到项目开发中 ...

  2. DPDK简介和原理

    本文分享自天翼云开发者社区<DPDK简介和原理>,作者:s****n DPDK是一种绕过内核直接在用户态收发包来解决内核性能的瓶颈技术. 什么是中断 了解DPDK之前,首先需要先了解什么是 ...

  3. 一个登录功能也能玩出这么多花样?sa-token带你轻松搞定多地登录、单地登录、同端互斥登录

    需求场景 说起登录,你可能会不屑一顾,还有比这更简单的功能吗? 获取一下用户提交参数 username + password 和数据库中一比对,有记录返回[登录成功],无记录返回[用户名或密码错误] ...

  4. 【忍者算法】从扫雷游戏到矩阵操作:探索矩阵置零问题|LeetCode 73 矩阵置零

    从扫雷游戏到矩阵操作:探索矩阵置零问题 生活中的算法 想象你在玩扫雷游戏,当你点到一个地雷时,不仅这个格子会被标记,与它同行同列的格子也都会受到影响.或者想象一个办公室的座位表,如果某个位置发现了感染 ...

  5. Luogu P3177 树上染色 [ 蓝 ] [ 树形 dp ] [ 贡献思维 ]

    一道很好的树形 dp !!!!! 树上染色. 错误思路 定义 \(dp[u][i]\) 表示以 \(u\) 为根的子树中,把 \(i\) 个点染成黑色的最大收益. 但这样写,就在转移的时候必须枚举每一 ...

  6. 并发编程 - 线程同步(七)之互斥锁Monitor

    通过前面对锁lock的基本使用以及注意事项的学习,相信大家对锁的同步机制有了大致了解,今天我们将继续学习--互斥锁Monitor. lock是C#语言中的关键字,是语法糖,lock语句最终会由C#编译 ...

  7. [BZOJ4671] 异或图 题解

    我能说什么!抽象了这! 看到 \(n\le 10\) 的黑题顿感大事不妙. 我们考虑设 \(f(i)\) 表示将 \(n\) 个点划分为至少 \(i\) 个连通块时的方案数.我们可以暴力枚举每个点在哪 ...

  8. 从龟速乘到 $Miller-Rabin$ 算法(数论算法总结)

    发现自己竟然菜到不太会龟速乘,所以把 \(Miller-Rabin\) 算法所需要用到的算法全学了一遍-- 龟速乘 龟速乘是一种 \(O(\log n)\) 的乘法计算方法. 考虑有时普通乘法取模会爆 ...

  9. FANUCR2000iB发那科机器人保养有哪些

      1.机器人保养的重要性   机器人都需要预防性保养,这样可以保证它们在生产线上保持最佳性能和实现一致性.当机器人没有进行定期的预防性保养检查,可能会导致零部件损坏或故障,从而致使生产放慢甚至停机. ...

  10. 【BUUCTF】AreUSerialz

    [BUUCTF]AreUSerialz (反序列化) 题目来源 收录于:BUUCTF 网鼎杯 2020 青龙组 题目描述 根据PHP代码进行反序列化 <?php include("fl ...