Java 根据cron表达式,获取quartz job执行时间

1.借助quartz中的工具类TriggerUtils,获取当前和下一次触发时间.
TriggerUtils.computeFireTimesBetween(cronTriggerImpl, null, fromDate ,toDate)

Java 根据cron表达式,获取quartz job执行时间_第1张图片

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));
        });
    }
}

Java 根据cron表达式,获取quartz job执行时间_第2张图片

你可能感兴趣的:(java,开发语言)