定时任务cron 解析为中文


在使用定时任务(quartz)时,其中的cron表达式除开发者以外的小伙伴很难看懂,我就自己写的一个将cron解析为中文,如果有问题请将提出来

1 package com.demo.util;
  2 
  3 import com.demo.enums.WeekEnum;
  4 import com.demo.entity.CronEntity;
  5 import org.apache.commons.lang.StringUtils;
  6 import org.assertj.core.util.Lists;
  7 import org.quartz.CronExpression;
  8 import org.springframework.util.Assert;
  9 
 10 import java.text.ParseException;
 11 import java.util.Date;
 12 import java.util.List;
 13 
 14 /**
 15  * ************************************************
 16  * 功能描述:   TODO
 17  *
 18  * @author shuangping.yang
 19  * @version 1.0
 20  * @ClassName CronExpParserUtil
 21  * @date 2020.08.18 上午 10:42 创建文件
 22  * @see ************************************************
 23  */
 24 public class CronExpParserUtil {
 25 
 26 
 27     /**
 28      * 解析corn表达式为中文
 29      *
 30      * @param cronExp
 31      * @return
 32      */
 33     public static String translateToChinese(String cronExp) {
 34         Assert.hasText(cronExp, "cron表达式为空!");
 35         Assert.isTrue(CronExpression.isValidExpression(cronExp), "cron表达式错误,请重新生成!");
 36         List<String> tmpCorns = Lists.newArrayList(cronExp.split(" "));
 37         StringBuilder sBuffer = new StringBuilder();
 38         if (tmpCorns.size() == 6) {
 39             //解析月
 40             sBuffer.append(strEquals(tmpCorns.get(4), "月"));
 41             //解析周
 42             String five = tmpCorns.get(5);
 43             if (!"*".equals(five) && !"?".equals(five)) {
 44                 char[] tmpArray = five.toCharArray();
 45                 for (char c : tmpArray) {
 46                     String week = WeekEnum.name(String.valueOf(c));
 47                     sBuffer.append(StringUtils.isNotEmpty(week) ? week : c);
 48                 }
 49             }
 50             //解析日
 51             String three = tmpCorns.get(3);
 52             sBuffer.append(!three.equals("?") ? strEquals(three, "日") : "");
 53             //解析时
 54             sBuffer.append(strEquals(tmpCorns.get(2), "时"));
 55             //解析分
 56             sBuffer.append(strEquals(tmpCorns.get(1), "分"));
 57             //解析秒
 58             sBuffer.append(strEquals(tmpCorns.get(0), "秒"));
 59         }
 60         return sBuffer.toString();
 61 
 62     }
 63 
 64     private static String strEquals(String tmpCorn, String str) {
 65         String division = "*";
 66         return division.equals(tmpCorn) ? "每" + str : tmpCorn + str;
 67     }
 68 
 69     /**
 70      * 根据cron反解析为时间列表
 71      *
 72      * @param cron 表达式
 73      * @return
 74      * @throws NormalException
 75      */
 76     public JobTimeCronResp getCronNextTime(String cron) {
 77         CronEntity resp = new CronEntity();
 78         List<String> cronList = Lists.newArrayList();
 79         if (StringUtils.isEmpty(cron)) {
 80             resp.setErrorMsg("cron表达式不能为空!");
 81             return resp;
 82         }
 83         resp.setCron(cron);
 84         if (CronExpression.isValidExpression(cron)) {
 85             CronExpression exp = null;
 86             try {
 87                 exp = new CronExpression(cron);
 88                 Date dd = new Date();
 89                 int i = 1;
 90                 while (i < 6) {
 91                     dd = exp.getNextValidTimeAfter(dd);
 92                     cronList.add(DateUtil.formatDate(dd, DateUtil.yyyyMMddHHmmss_EN));
 93                     dd = new Date(dd.getTime() + 1000);
 94                     i++;
 95                 }
 96             } catch (ParseException e) {
 97                 resp.setErrorMsg("cron表达式错误,请重新生成!");
 98                 return resp;
 99             }
100             resp.setNextValidTime(cronList);
101         } else {
102             resp.setErrorMsg("cron表达式错误,请重新生成!");
103             return resp;
104         }
105         return resp;
106     }
107 
108     //测试方法
109     public static void main(String[] args) {
110         String CRON_EXPRESSION = "0 0 0 ? * 2,3";
111         // 生成指定日期的CRON时间序列
112         System.out.println(CRON_EXPRESSION);
113         System.out.println(translateToChinese(CRON_EXPRESSION));
114     }
115 }

package com.demo.enums;

/**
 * WeekEnum
 *
 * @author shuangping.yang
 */
public enum WeekEnum {
    SUNDAY("1", "星期天"),
    MONDAY("2", "星期一"),
    TUESDAY("3", "星期二"),
    WEDNESDAY("4", "星期三"),
    THURSDAY("5", "星期四"),
    FRIDAY("6", "星期五"),
    SATURDAY("7", "星期六"),
    TO("-", "至");
    private String key;
    private String name;

    WeekEnum(String key, String name) {
        this.key = key;
        this.name = name;
    }

    public static String name(String code) {
        for (WeekEnum m : WeekEnum.values()) {
            if (m.getKey().equals(code)) {
                return m.getName();
            }
        }
        return "";
    }

    public static String key(String name) {
        for (WeekEnum m : WeekEnum.values()) {
            if (m.getName().equals(name)) {
                return m.getKey();
            }
        }
        return "";
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

枚举类

1 package com.demo.entity;
 2 
 3 import io.swagger.annotations.ApiModelProperty;
 4 import lombok.Data;
 5 
 6 import java.io.Serializable;
 7 import java.util.List;
 8 
 9 /**
10  * ************************************************
11  * 功能描述:   TODO 根据cron表达式方向生成运行时间
12  *
13  * @author shuangping.yang
14  * @version 1.0
15  * @ClassName JobTimeCronResp
16  * @date 2020/4/27 14:06 创建文件
17  * @see ************************************************
18  */
19 @Data
20 public class CronEntity implements Serializable {
21 
22     private static final long serialVersionUID = 8029641231229691702L;
23 
24     @ApiModelProperty(name = "cron表达式")
25     private String cron;
26 
27     @ApiModelProperty(name = "最近5次执行时间")
28     private List<String> nextValidTime;
29 
30     @ApiModelProperty(name = "错误信息")
31     private String errorMsg;
32 
33 }

解析返回实体


原文链接:https://www.cnblogs.com/yangshus/p/13522228.html