public class CronUtil {
public static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
public static SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
//上次执行时间
public static long getLastTriggerTime(String cron) {
String[] s = cron.split("\\?");
cron = s[0] + " \\?";
Date date = new Date();
CronSequenceGenerator cronSequenceGenerator = new CronSequenceGenerator(cron);
Date time1 = cronSequenceGenerator.next(date);//下次执行时间
Date time2 = cronSequenceGenerator.next(time1);
Date time3 = cronSequenceGenerator.next(time2);
long l = time1.getTime() - (time3.getTime() - time2.getTime());
return l;
}
//获取下次执行时间(getFireTimeAfter,也可以下下次...)
public static long getNextTriggerTime(String cron) {
String[] s = cron.split("\\?");
cron = s[0] + " \\?";
Date date = new Date();
CronSequenceGenerator cronSequenceGenerator = new CronSequenceGenerator(cron);
Date time1 = cronSequenceGenerator.next(date);//下次执行时间
return time1.getTime();
}
// 获取今天所有执行时间
public static void getTodayExceuteTime(String cron) {
try {
Date nextTime = df.parse(df2.format(new Date()) + " 00:00:00");
Date to = new Date(nextTime.getTime() + 24 * 3600 * 1000);
CronSequenceGenerator cronSequenceGenerator = new CronSequenceGenerator(cron);
List<Date> crontimes = new ArrayList<>();
for (; nextTime.getTime() <= to.getTime(); ) {
nextTime = cronSequenceGenerator.next(nextTime);
if (nextTime.getTime() <= to.getTime()) {
crontimes.add(nextTime);
}
}
for (int i = 0; i < crontimes.size(); i++) {
System.out.println(df.format(crontimes.get(i)));
}
} catch (ParseException e) {
e.printStackTrace();
}
}
// 测试
public static void main(String[] args) {
String cron = "0 5 * * * ?";
getTodayExceuteTime(cron);
}
//结果
2021-08-23 00:05:00
2021-08-23 01:05:00
2021-08-23 02:05:00
2021-08-23 03:05:00
2021-08-23 04:05:00
2021-08-23 05:05:00
2021-08-23 06:05:00
2021-08-23 07:05:00
2021-08-23 08:05:00
2021-08-23 09:05:00
2021-08-23 10:05:00
2021-08-23 11:05:00
2021-08-23 12:05:00
2021-08-23 13:05:00
2021-08-23 14:05:00
2021-08-23 15:05:00
2021-08-23 16:05:00
2021-08-23 17:05:00
2021-08-23 18:05:00
2021-08-23 19:05:00
2021-08-23 20:05:00
2021-08-23 21:05:00
2021-08-23 22:05:00
2021-08-23 23:05:00