根據cron表達式獲取最近幾次執行的時間
最近有個新需求,就是現在有個定時任務,前端需要展示出最近一次的具體執行時間:
具體可有以下兩種做法(可能更多),個人推薦方式一
方式一:指定獲取的最近執行的次數
首先maven引入依賴(本來就有定時任務的,此步驟僅又來做個人測試)
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
直接貼上method
/**
*
* @param cronExpression cron表達式
* @param numTimes 下一(幾)次運行的時間
* @return
*/
public static List<String> getNextExecTime(String cronExpression,Integer numTimes) {
List<String> list = new ArrayList<>();
CronTriggerImpl cronTriggerImpl = new CronTriggerImpl();
try {
cronTriggerImpl.setCronExpression(cronExpression);
} catch(ParseException e) {
e.printStackTrace();
}
// 這個是重點,一行代碼搞定
List<Date> dates = TriggerUtils.computeFireTimes(cronTriggerImpl, null, numTimes);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (Date date : dates) {
list.add(dateFormat.format(date));
}
return list;
}
方式二:獲取指定時間內(可以自己指定年或月或日)所有的執行時間,然后在所有的時間內取前幾個(不推薦,當觸發時間過短,程序響應時間非常長)
廢話不多說,直接上method
/**
* @param cronExpression cron表達式
* @param numTimes 下一(幾)次運行的時間
* @return
*/
public static List<String> getRecentExecTime(String cronExpression, Integer numTimes) {
List<String> list = new ArrayList<>();
try {
CronTriggerImpl cronTrigger = new CronTriggerImpl();
cronTrigger.setCronExpression(cronExpression);
// 這里寫要准備猜測的cron表達式
Calendar calendar = Calendar.getInstance();
Date now = calendar.getTime();
// 把統計的區間段設置為從現在到2年后的今天(主要是為了方法通用考慮,如那些1個月跑一次的任務,如果時間段設置的較短就不足20條)
calendar.add(Calendar.YEAR, 2);
// 這個是重點,一行代碼搞定
List<Date> dates = TriggerUtils.computeFireTimesBetween(cronTrigger, null, now, calendar.getTime());
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for(int i = 0; i < dates.size(); i++) {
// 這個是提示的日期個數
if(i < numTimes) {
list.add(dateFormat.format(dates.get(i)));
}else {
break;
}
}
} catch(ParseException e) {
e.printStackTrace();
}
return list;
}
轉自:https://blog.csdn.net/macro_g/article/details/81668409
