根据cron表达式计算最近几次的执行时间

使用场景:

使用quartz做为后台任务调度框架,cron表达式设置时间,需要根据cron表达式计算出最近n次的执行具体时间--这个通常在开放给用户修改任务执行时间给出提示时非常有用

解决:

使用quartz的jar包中提供的TriggerUtils类来计算

具体代码:

package com.crazycoder2010.quartz;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.quartz.TriggerUtils;
import org.quartz.impl.triggers.CronTriggerImpl;

public class Main {
    
    /**
    * @param args
    * @throws ParseException 
     * @throws InterruptedException 
     */
    public static void main(String[] args) throws ParseException, InterruptedException {
       CronTriggerImpl cronTriggerImpl = new CronTriggerImpl();
       cronTriggerImpl.setCronExpression("0 0 15 5 * ?");//这里写要准备猜测的cron表达式
       Calendar calendar = Calendar.getInstance();
       Date now = calendar.getTime();
       calendar.add(Calendar.YEAR, 2);//把统计的区间段设置为从现在到2年后的今天(主要是为了方法通用考虑,如那些1个月跑一次的任务,如果时间段设置的较短就不足20条)
       List<Date> dates = TriggerUtils.computeFireTimesBetween(cronTriggerImpl, null, now, calendar.getTime());//这个是重点,一行代码搞定~~
       System.out.println(dates.size());
       SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
       for(int i =0;i < dates.size();i ++){
           if(i >19){//这个是提示的日期个数
              break;
           }
           System.out.println(dateFormat.format(dates.get(i)));
       }
    }

}




  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值