1.借助quartz中的工具类TriggerUtils,获取当前和下一次触发时间.
TriggerUtils.computeFireTimesBetween(cronTriggerImpl, null, fromDate ,toDate)
2.测试code(前提: 需要导入quartz依赖)
package boot.spring.quartz;
import org.quartz.TriggerUtils;
import org.quartz.impl.triggers.CronTriggerImpl;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.List;
public class CronUtils {
public static void main(String[] args) throws ParseException {
CronTriggerImpl cronTriggerImpl = new CronTriggerImpl();
cronTriggerImpl.setCronExpression("0 0/30 * * * ?");// 30分钟执行一次
OffsetDateTime odt = OffsetDateTime.now();
ZoneOffset zoneOffset = odt.getOffset();
LocalDateTime now = LocalDateTime.now();
// 当前触发的时间
LocalDateTime lastTime = now.minusMinutes(30);
LocalDateTime nextTime = now.plusMinutes(30);
Date lastDate = Date.from(lastTime.toInstant(ZoneOffset.of(zoneOffset.toString())));
Date nextDate = Date.from(nextTime.toInstant(ZoneOffset.of(zoneOffset.toString())));
//
List lastAndNextTimes = TriggerUtils.computeFireTimesBetween(cronTriggerImpl, null, lastDate ,nextDate);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
lastAndNextTimes.forEach(date -> {
System.out.println(dateFormat.format(date));
});
}
}