根据时间范围生成cron 表达式

本文介绍了一种根据开始时间和结束时间生成Cron表达式的方法,并提供了验证Cron表达式有效性的函数,同时展示了如何获取任务在未来一段时间内的具体执行时间。

 1.cron表达式没有时间范围的,用多个表达式来体现时间范围(每分钟执行一次)

/**
     * 时间范围
     * */
    public static String createCronExpression(String beginTime ,String endTime){
        //拆分时间字符串 年,月,日,时,分,秒
        String[] beginDate = beginTime.split(" |-|:");
        String[] endDate = endTime.split(" |-|:");
        //计算两个日期之间相差的月数
        int diffMonth = TimeUtil.getDiffMonth(Convert.toDate(beginTime), Convert.toDate(endTime));
        //返回指定年月的月的最后一天
        Date day = TimeUtil.getLastDayOfMonth(Convert.toInt((beginDate[0])), Convert.toInt((beginDate[1])));
        StringBuffer cronExp = new StringBuffer("");
        if(beginDate[0].equals(endDate[0])
                &&beginDate[1].equals(endDate[1])
                &&beginDate[2].equals(endDate[2])){
            //同一天时间
             getDAY(cronExp, beginDate,beginDate[4],"/",1);
             cronExp.append(",");
             getMothDayHour(cronExp, Convert.toInt(beginDate[3]) + 1, Convert.toInt(endDate[3]) - 1, beginDate[2], beginDate[1]);
             cronExp.append(",");
             getDAY(cronExp,endDate,0,"-",endDate[4]);
             cronExp.append(",");
        }else {
            if(Convert.toInt(beginDate[3])<23){
                getDAY(cronExp, beginDate,beginDate[4],"/",1);
                cronExp.append(",");
                getMothDayHour(cronExp, Convert.toInt(beginDate[3]) + 1, 23, beginDate[2], beginDate[1]);
                cronExp.append(",");
            }else {
                getDAY(cronExp, beginDate,beginDate[4],"/",1);
                cronExp.append(",");
            }
            if(beginDate[0].equals(endDate[0])){
                //同年且同月
                if(beginDate[1].equals(endDate[1])){
                    getMothYear(cronExp,Convert.toInt((beginDate[2])) + 1, Convert.toInt(endDate[2]) - 1, beginDate[1]);
                }else if (Convert.toInt((beginDate[1]))<Convert.toInt(endDate[1])){
                    //同年不同月
                    //间隔只有一个月
                    if(diffMonth==1){
                        getMothYear(cronExp,Convert.toInt((beginDate[2]))+1,day.getDate(),beginDate[1]);
                        cronExp.append(",");
                        getMothYear(cronExp,1,Convert.toInt(endDate[2])-1,beginDate[1]);
                    }else if(diffMonth>1){
                        getMothYear(cronExp,Convert.toInt((beginDate[2]))+1,day.getDate(),beginDate[1]);
                        cronExp.append(",");
                        getMoth(cronExp,Convert.toInt((beginDate[1]))+1,Convert.toInt((endDate[1]))-1);
                        cronExp.append(",");
                        getMothYear(cronExp,1,Convert.toInt(endDate[2])-1,endDate[1]);
                    }
                }
            }else if(Convert.toInt(beginDate[0])<Convert.toInt(endDate[0])){
                //不同年
                cronExp=getMothYear(cronExp,Convert.toInt((beginDate[2]))+1,day.getDate(),beginDate[1]);
                if(Convert.toInt((beginDate[1]))<12){
                    cronExp.append(",");
                    getMoth(cronExp,Convert.toInt((beginDate[1]))+1,12);
                }
                if(Convert.toInt(endDate[1])-1==0&&Convert.toInt(endDate[2])-1>0){
                    cronExp.append(",");
                    getMothYear(cronExp,1,Convert.toInt((endDate[2]))-1,endDate[1]);
                }else {
                    cronExp.append(",");
                    getMoth(cronExp,1,Convert.toInt((endDate[1]))-1);
                    cronExp.append(",");
                    getMothYear(cronExp,1,Convert.toInt((endDate[2]))-1,endDate[1]);
                }
            }
            cronExp.append(",");
            getMothDayHour(cronExp,0,Convert.toInt(endDate[3])-1,endDate[2],endDate[1]);
            cronExp.append(",");
            getDAY(cronExp, endDate,0,"-",endDate[4]);
        }

        return cronExp.toString();
    }

    /**日,月,时,分*/
    public  static StringBuffer getDAY(StringBuffer cronExp,String[] strings,Object beginMin,String symbol,Object endMin){
        cronExp.append(0).append(" ");
        cronExp.append(beginMin).append(symbol).append(endMin).append(" ");
        cronExp.append(strings[3]).append(" ");//小时
        cronExp.append(strings[2]).append(" ");//日
        cronExp.append(strings[1]).append(" ");//月
        cronExp.append("?");//周
        return cronExp;
    }

    /**日、月、时*/
    public static StringBuffer getMothDayHour(StringBuffer cronExp,Object beginHour,Object endHour,String day ,String moth){
        //秒  取整,精确到分钟
        cronExp.append(0).append(" ");
        cronExp.append("*").append(" ");
        cronExp.append(beginHour).append("-").append(endHour).append(" ");//小时
        cronExp.append(day).append(" ");//日
        cronExp.append(moth).append(" ");//月
        cronExp.append("?");//周
        return cronExp;
    }

    /**
     * 日、月
     * */
    public static StringBuffer getMothYear(StringBuffer cronExp,Object beginDay,Object endDay,String moth){

        //秒
        cronExp.append(0).append(" ");
        //每分钟
        cronExp.append("*").append(" ");
        cronExp.append("*").append(" ");//小时
        cronExp.append(beginDay).append("-").append(endDay).append(" ");//日
        cronExp.append(moth).append(" ");//月
        cronExp.append("?");//周
        return cronExp;
    }

    /**月*/
    public static StringBuffer getMoth(StringBuffer cronExp,Integer beginoth,Integer endMoth){

        //秒
        cronExp.append(0).append(" ");
        //每分钟
        cronExp.append("*").append(" ");
        cronExp.append("*").append(" ");//小时
        cronExp.append("*").append(" ");//日
        cronExp.append(beginoth).append("-").append(endMoth).append(" ");//月
        cronExp.append("?");//周
        return cronExp;
    }



    /**补全时间
     * type:1:分钟,2:小时,3:日
     * */

    public static String time(Integer type,String time){
         if(type==1){
            //精确到分钟,补全秒
            time=time+":00";
         }else if(type==2){
             //精确到小时,补全分、秒
             time=time+":00:00";
         }else if(type==3){
             //精确到日,补全时、分、秒
             time=time+"  00:00:00";
         }
         return time;
    }

2.上面生成的表达式可以根据下面的方法测试下,看看是否是自己想要的

//依赖
<dependency>
   <groupId>org.quartz-scheduler</groupId>
   <artifactId>quartz</artifactId>
   <version>2.3.0</version>
</dependency>
  /**
         * 根据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;
        }


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值