import org.quartz.TriggerUtils;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.triggers.CronTriggerImpl;
public static Date getNTimeByCron(String cron) {
try {
//根據cron算出該任務的下次執行時間
CronTriggerImpl cronTriggerImpl = new CronTriggerImpl();
cronTriggerImpl.setCronExpression(cron);
Calendar calendar = Calendar.getInstance();
Date now = calendar.getTime();
// 把統計的區間段設置為從現在到2年后的今天(主要是為了方法通用考慮,如那些1個月跑一次的任務,如果時間段設置的較短就不足20條)
calendar.add(Calendar.YEAR, 2);
// 這個是重點,一行代碼搞定
List<Date> dates = TriggerUtils.computeFireTimesBetween(cronTriggerImpl, null, now, calendar.getTime());
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String nextTime = dateFormat.format(dates.get(0));
Date date=dateFormat.parse(nextTime);
return date;
} catch (Exception e) {
throw new RuntimeException(e);
}
}