Jade Dungeon

Quartz定时任务

Cron表达式

注意Apache Quartz和Spring对Cron表达式中关于星期几的定义不同,一个是从周一开始一个是从周日开始:

使用Apache Quartz得到cron表达式在指定时间区间内触发的时间:

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

import org.apache.commons.lang3.StringUtils;
import org.quartz.CronExpression;



	/**
	 * 
	 * @param cron      cron exp
	 * @param startTime start time
	 * @param endTime   end time
	 * @return
	 * @throws ParseException
	 * @throws IllegalArgumentException
	 */
	public static List<Date> seeExcuteTime(String expression, long startTime, long endTime)
			throws ParseException, IllegalArgumentException //
	{
		if (StringUtils.isEmpty(expression)) {
			throw new IllegalArgumentException("参数不能为空");
		}
		if (startTime > endTime) {
			throw new IllegalArgumentException("开始时间大于结束时间");
		}

//		CronSequenceGenerator cronSequenceGenerator = new CronSequenceGenerator(expression);
		CronExpression ce = new CronExpression(expression);
		List<Date> list = new ArrayList<>(10);
		long nextTimePoint = startTime;
		while (nextTimePoint < endTime) {
//			Date d = cronSequenceGenerator.next(new Date(nextTimePoint));
			Date d = ce.getNextValidTimeAfter(new Date(nextTimePoint));
			if (null == d || d.getTime() > endTime) {
				break;
			}
			nextTimePoint = d.getTime();
			list.add(d);
		}
		return list;
	}

Spring定时任务得到cron表达式在指定时间区间内触发的时间:

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

import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.support.CronSequenceGenerator;


	/**
	 * 
	 * @param cron      cron exp
	 * @param startTime start time
	 * @param endTime   end time
	 * @return
	 * @throws ParseException
	 * @throws IllegalArgumentException
	 */
	public static List<Date> seeExcuteTime(String expression, long startTime, long endTime)
			throws ParseException, IllegalArgumentException //
	{
		if (StringUtils.isEmpty(expression)) {
			throw new IllegalArgumentException("参数不能为空");
		}
		if (startTime > endTime) {
			throw new IllegalArgumentException("开始时间大于结束时间");
		}

//		CronSequenceGenerator cronSequenceGenerator = new CronSequenceGenerator(expression);
		CronExpression ce = new CronExpression(expression);
		List<Date> list = new ArrayList<>(10);
		long nextTimePoint = startTime;
		while (nextTimePoint < endTime) {
//			Date d = cronSequenceGenerator.next(new Date(nextTimePoint));
			Date d = ce.getNextValidTimeAfter(new Date(nextTimePoint));
			if (null == d || d.getTime() > endTime) {
				break;
			}
			nextTimePoint = d.getTime();
			list.add(d);
		}
		return list;
	}