1. 程式人生 > 其它 >定時任務Cron工具類

定時任務Cron工具類

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