Cron工具获取上次执行时间和下次执行时间
Posted 抓手
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Cron工具获取上次执行时间和下次执行时间相关的知识,希望对你有一定的参考价值。
spring的CronSequenceGenerator工具不支持7位cron表达式,也不支持含非数字"L"的表达式:
IllegalArgumentException: Cron expression must consist of 6 fields (found 7 in "34 20 18 L 1/3 ? *")
NumberFormatException: For input string: "L"
后来在GitHub上找到一个工具:GitHub - jmrozanec/cron-utils: Cron utils for parsing, validations and human readable descriptions as well as date/time interoperability.
<dependency>
<groupId>com.cronutils</groupId>
<artifactId>cron-utils</artifactId>
<version>9.1.5</version>
</dependency>
然后自定义封装了一下:
import com.cronutils.model.Cron;
import com.cronutils.model.definition.CronDefinition;
import com.cronutils.model.definition.CronDefinitionBuilder;
import com.cronutils.model.time.ExecutionTime;
import com.cronutils.parser.CronParser;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.util.Optional;
import static com.cronutils.model.CronType.QUARTZ;
/**
* @author 向振华
* @date 2021/09/13 09:33
*/
public class CronUtils {
private static final CronDefinition CRON_DEFINITION = CronDefinitionBuilder.instanceDefinitionFor(QUARTZ);
public static LocalDateTime lastExecution(String expression) {
CronParser parser = new CronParser(CRON_DEFINITION);
Cron quartzCron = parser.parse(expression);
ZonedDateTime now = ZonedDateTime.now();
ExecutionTime executionTime = ExecutionTime.forCron(quartzCron);
Optional<ZonedDateTime> zonedDateTimeOptional = executionTime.lastExecution(now);
if (zonedDateTimeOptional.isPresent()) {
ZonedDateTime zonedDateTime = zonedDateTimeOptional.get();
return zonedDateTime.toLocalDateTime();
}
return null;
}
public static LocalDateTime nextExecution(String expression) {
CronParser parser = new CronParser(CRON_DEFINITION);
Cron quartzCron = parser.parse(expression);
ZonedDateTime now = ZonedDateTime.now();
ExecutionTime executionTime = ExecutionTime.forCron(quartzCron);
Optional<ZonedDateTime> zonedDateTimeOptional = executionTime.nextExecution(now);
if (zonedDateTimeOptional.isPresent()) {
ZonedDateTime zonedDateTime = zonedDateTimeOptional.get();
return zonedDateTime.toLocalDateTime();
}
return null;
}
}
测试:
表达式:34 20 18 L 1/3 ?
以上是关于Cron工具获取上次执行时间和下次执行时间的主要内容,如果未能解决你的问题,请参考以下文章
如何在 ColdFusion 中获取计划任务列表和上次运行结果?