概述:
Quartz是一个开源的、轻量级的调度框架,它允许在指定时间或以某个频率执行作业。在使用Quartz时,需要引入Quartz依赖,这样就可以在项目中使用Quartz提供的调度功能。
本文将着重介绍Quartz中获取运行时间的功能。但是目前没有已有的开箱即用的api,分别用于获取指定cron表达式在当前时间之后和之前的若干次运行时间,所以我实现了一下两个函数:computeFireTimesAfter()和computeFireTimesPre()
具体实现时,我们可以通过传入cron表达式和需要获取的次数来调用这两个方法。computeFireTimesAfter()方法会获取指定cron表达式在当前时间之后的若干次运行时间,而computeFireTimesPre()方法会获取指定cron表达式在当前时间之前的若干次运行时间。
在实现这两个方法时,我们需要先实例化一个CronTriggerImpl对象,并设置其cron表达式。然后,通过调用getFireTimeAfter()方法来获取下一次运行时间。为了获取多次运行时间,我们需要在一个循环中不断调用getFireTimeAfter()方法,并将当前时间更新为下一次运行时间。为了方便使用,我们还提供了一个日期格式化方法,将Date类型的时间转换成字符串格式的时间。
1. 引入quartz依赖
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.0</version>
</dependency>
2. 获取运行时间
a. 之后几次运行时间:
传入参数:cron表达式, 运行次数
public static List<String> computeFireTimesAfter(String cron, int count) throws ParseException {
List<String> runTime = Lists.newArrayList();
// 实例化trigger
CronTriggerImpl cronTrigger = new CronTriggerImpl();
cronTrigger.setCronExpression(new CronExpression(cron));
// 获取当前时间
Date currentTime = new Date();
while (count-- > 0) {
// 获取下次运行时间
Date nextFireTime = cronTrigger.getFireTimeAfter(currentTime);
String formattedDateTime = formatTime(nextFireTime);
runTime.add(formattedDateTime);
// 更新当前时间为下次运行时间
currentTime = nextFireTime;
}
return Collections.unmodifiableList(runTime);
}
b. 之前几次运行时间:
传入参数:cron表达式, 运行次数
public static Set<String> computeFireTimesPre(String cron, int count) throws ParseException {
Calendar calendar = Calendar.getInstance();
Date now = calendar.getTime();
CronTriggerImpl cronTrigger = new CronTriggerImpl();
cronTrigger.setCronExpression(cron);
Set<String> set = new LinkedHashSet<>();
while (set.size() < count) {
// 获取前一个月时间
calendar.add(Calendar.MONTH, -1);
List<String> dates = TriggerUtils.computeFireTimesBetween(
cronTrigger, null, calendar.getTime(), now).stream().map(each -> formatTime(each)).collect(Collectors.toList());
Collections.reverse(dates);
// 满足期待获取次数则退出循环,否则再向前推一个月获取运行时间
if (dates.size() < count) {
set.addAll(dates);
} else {
set.addAll(dates.subList(0, count));
}
}
return set;
}
c. 日期格式化
private static String formatTime(Date nextFireTime) {
LocalDateTime localDateTime = LocalDateTime.ofInstant(nextFireTime.toInstant(), ZoneId.systemDefault());
String formattedDateTime = localDateTime.format(COMMON_TIME_PATTERN);
return formattedDateTime;
}