【修复】定时任务指定某一年执行时,只会执行一次,后台查看任务详细会报错

This commit is contained in:
YunaiV 2024-06-15 17:57:13 +08:00
parent e06fc83519
commit 7eaddd16f9

View File

@ -34,24 +34,24 @@ public class CronUtils {
* @return 满足条件的执行时间 * @return 满足条件的执行时间
*/ */
public static List<LocalDateTime> getNextTimes(String cronExpression, int n) { public static List<LocalDateTime> getNextTimes(String cronExpression, int n) {
// 获得 CronExpression 对象 // 1. 获得 CronExpression 对象
CronExpression cron; CronExpression cron;
try { try {
cron = new CronExpression(cronExpression); cron = new CronExpression(cronExpression);
} catch (ParseException e) { } catch (ParseException e) {
throw new IllegalArgumentException(e.getMessage()); throw new IllegalArgumentException(e.getMessage());
} }
// 从当前开始计算n 个满足条件的 // 2. 从当前开始计算n 个满足条件的
Date now = new Date(); Date now = new Date();
List<LocalDateTime> nextTimes = new ArrayList<>(n); List<LocalDateTime> nextTimes = new ArrayList<>(n);
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
Date nextTime = cron.getNextValidTimeAfter(now); Date nextTime = cron.getNextValidTimeAfter(now);
// 2.1 如果 nextTime null说明没有更多的有效时间退出循环
if (nextTime == null) { if (nextTime == null) {
// 如果 nextTime null说明没有更多的有效时间退出循环
break; break;
} }
nextTimes.add(LocalDateTimeUtil.of(nextTime)); nextTimes.add(LocalDateTimeUtil.of(nextTime));
// 切换现在为下一个触发时间 // 2.2 切换现在为下一个触发时间
now = nextTime; now = nextTime;
} }
return nextTimes; return nextTimes;