在使用Quartz进行任务调度时,需要用到Cron表达式,有时候在设置完Cron表达式之后,需要知道此cron表达式对应的最近几次执行的具体时间,我这里提供了一个方法来获取最近几次的运行时间。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89package com.declan; import java.text.SimpleDateFormat; import java.util.Date; import org.quartz.CronExpression; import org.quartz.CronScheduleBuilder; import org.quartz.CronTrigger; import org.quartz.TriggerBuilder; /** * 通过Cron表达式获取近5次的执行时间 * @author Declan * */ public class GetScheduleTimeOfCron { public static void main(String[] args) { System.out.println(getCronSchdule("1 3 8 * * ?")); } /** * 根据Cron表达式获取任务最近5次的执行时间 * @param cron * @return */ public static String getCronSchdule(String cron){ String timeSchdule=""; if(!CronExpression.isValidExpression(cron)){ return "Cron is Illegal!"; } try { CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity("Caclulate Date").withSchedule(CronScheduleBuilder.cronSchedule(cron)).build(); Date time0 = trigger.getStartTime(); Date time1 = trigger.getFireTimeAfter(time0); Date time2 = trigger.getFireTimeAfter(time1); Date time3 = trigger.getFireTimeAfter(time2); Date time4 = trigger.getFireTimeAfter(time3); Date time5 = trigger.getFireTimeAfter(time4); SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); StringBuilder timeBuilder=new StringBuilder(); timeBuilder .append(format.format(time1)) .append("n") .append(format.format(time2)) .append("n") .append(format.format(time3)) .append("n") .append(format.format(time4)) .append("n") .append(format.format(time5)); timeSchdule=timeBuilder.toString(); } catch (Exception e) { timeSchdule="unKnow Time!"; } return timeSchdule; } /** * 根据Cron表达式获取任务最近 几次的执行时间 * @param cron cron表达式 * @param count 次数 * @return */ public static List<String> getCronSchdule(String cron, int count){ List<String> retList = new ArrayList<String>(); if(!CronExpression.isValidExpression(cron)){ //Cron表达式不正确 return retList; } try { CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity("Caclulate Date").withSchedule(CronScheduleBuilder.cronSchedule(cron)).build(); SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date startTime = trigger.getStartTime(); for (int i = 0; i < count; i++) { Date time = trigger.getFireTimeAfter(startTime); retList.add(format.format(time )); startTime = time; } } catch (Exception e) { logger.error("", e); } return retList; } }
运行后的结果
复制代码
1
2
3
4
5
62018-04-20 08:03:01 2018-04-21 08:03:01 2018-04-22 08:03:01 2018-04-23 08:03:01 2018-04-24 08:03:01
转载于:https://my.oschina.net/Declan/blog/1797719
最后
以上就是勤恳书本最近收集整理的关于根据Cron表达式获取近几次任务执行时间的全部内容,更多相关根据Cron表达式获取近几次任务执行时间内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复