在使用Quartz进行任务调度时,需要用到Cron表达式,有时候在设置完Cron表达式之后,需要知道此cron表达式对应的最近几次执行的具体时间,我这里提供了一个方法来获取最近几次的运行时间。
package com.declan;import java.text.SimpleDateFormat;import java.util.Date;import org.quartz.CronExpression;import org.quartz.CronScheduleBuilder;import org.quartz.CronTrigger;import org.quartz.TriggerBuilder;/** * 通过Cron表达式获取近5次的执行时间 * @author Declan * */public class GetScheduleTimeOfCron { public static void main(String[] args) { System.out.println(getCronSchdule("1 3 8 * * ?")); } /** * 根据Cron表达式获取任务最近5次的执行时间 * @param cron * @return */ public static String getCronSchdule(String cron){ String timeSchdule=""; if(!CronExpression.isValidExpression(cron)){ return "Cron is Illegal!"; } try { CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity("Caclulate Date").withSchedule(CronScheduleBuilder.cronSchedule(cron)).build(); Date time0 = trigger.getStartTime(); Date time1 = trigger.getFireTimeAfter(time0); Date time2 = trigger.getFireTimeAfter(time1); Date time3 = trigger.getFireTimeAfter(time2); Date time4 = trigger.getFireTimeAfter(time3); Date time5 = trigger.getFireTimeAfter(time4); SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); StringBuilder timeBuilder=new StringBuilder(); timeBuilder .append(format.format(time1)) .append("\n") .append(format.format(time2)) .append("\n") .append(format.format(time3)) .append("\n") .append(format.format(time4)) .append("\n") .append(format.format(time5)); timeSchdule=timeBuilder.toString(); } catch (Exception e) { timeSchdule="unKnow Time!"; } return timeSchdule; } /** * 根据Cron表达式获取任务最近 几次的执行时间 * @param cron cron表达式 * @param count 次数 * @return */ public static ListgetCronSchdule(String cron, int count){ List retList = new ArrayList (); if(!CronExpression.isValidExpression(cron)){ //Cron表达式不正确 return retList; } try { CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity("Caclulate Date").withSchedule(CronScheduleBuilder.cronSchedule(cron)).build(); SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date startTime = trigger.getStartTime(); for (int i = 0; i < count; i++) { Date time = trigger.getFireTimeAfter(startTime); retList.add(format.format(time )); startTime = time; } } catch (Exception e) { logger.error("", e); } return retList; }}
运行后的结果
2018-04-20 08:03:012018-04-21 08:03:012018-04-22 08:03:012018-04-23 08:03:012018-04-24 08:03:01