cron表达式获取上次执行时间和下次执行时间

  • Post author:
  • Post category:其他


package com.***;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.quartz.CronExpression;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerUtils;
import org.quartz.impl.triggers.CronTriggerImpl;

//见import,需要quartz jar包
public class CronUtil {
	
	//上次执行时间
	public static long getLastTriggerTime(String cron){
		if(!CronExpression.isValidExpression(cron)){
			return 0;
		}
		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);
		long l = time1.getTime() -(time3.getTime() -time2.getTime());
//		Date date = new Date(l);   
//		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    
		return l;
    }
    //获取下次执行时间(getFireTimeAfter,也可以下下次...)
	public static long getNextTriggerTime(String cron){
		if(!CronExpression.isValidExpression(cron)){
			return 0;
		}
		CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity("Caclulate Date").withSchedule(CronScheduleBuilder.cronSchedule(cron)).build();
		Date time0 = trigger.getStartTime();
		Date time1 = trigger.getFireTimeAfter(time0);
		return time1.getTime();
    }
}



版权声明:本文为sinaihalo原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。