【转】根据cron表达式获取最近几次执行的时间

根据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

猜你喜欢

转载自www.cnblogs.com/sanxiao/p/12346411.html
今日推荐