quartz踩过的坑-判断时间表达式是否可用
2019-10-17 本文已影响0人
boyiis
public class TaskUtils {
/**
* 校验定时任务格式
* @param expressionStr
* @return
*/
public static boolean isValidExpressionStr(String expressionStr){
if(StringUtil.isBlank(expressionStr)){
return false;
}
return CronExpression.isValidExpression(expressionStr);
}
/**
* 校验表达式是否能触发(相对于当前时间)
* @param expressionStr
* @return
* @throws ParseException
*/
public static boolean isCanDoExpression(String expressionStr) throws ParseException{
//先判断表达式格式是否正确
if(!isValidExpressionStr(expressionStr)){
return false;
}
CronTriggerImpl triggerImpl=new CronTriggerImpl();
triggerImpl.setCronExpression(expressionStr);
Date date=triggerImpl.computeFirstFireTime(null);
return date!=null&&date.after(new Date());
}
/**
* 获取一段时间内可以运行日期
* @param expressionStr
* @param beginDate
* @param endDate
* @return
* @throws ParseException
*/
public static List<Date> getCanDoBetween(String expressionStr,Date beginDate,Date endDate) throws ParseException{
//先判断表达式格式是否正确
if(!isValidExpressionStr(expressionStr)){
return null;
}
if(endDate.before(beginDate)){
return null;
}
CronTriggerImpl triggerImpl=new CronTriggerImpl();
triggerImpl.setCronExpression(expressionStr);
return TriggerUtils.computeFireTimesBetween(triggerImpl, null, beginDate, endDate);
}
public static void main(String[] args) throws ParseException {
Calendar calendar=Calendar.getInstance();
calendar.add(Calendar.YEAR, -1);
List<Date> resultList=getCanDoBetween("0 0 0/4 8 8 ?", calendar.getTime(), new Date());
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (Date date : resultList) {
System.out.println(sdf.format(date));
}
}
}