Cron表达式工具类CronUtil
构建Cron表达式
public static String createCronExpression(TaskScheduleModel taskScheduleModel){StringBuffer cronExp = new StringBuffer("");if(null == taskScheduleModel.getJobType()) {System.out.println("执行周期未配置" );}if (null != taskScheduleModel.getSecond()&& null != taskScheduleModel.getMinute()&& null != taskScheduleModel.getHour()) {cronExp.append(taskScheduleModel.getSecond()).append(" ");cronExp.append(taskScheduleModel.getMinute()).append(" ");cronExp.append(taskScheduleModel.getHour()).append(" ");if(taskScheduleModel.getJobType().getValue() == 1){if(taskScheduleModel.getBeApart()!=null){cronExp.append("1");cronExp.append("/");cronExp.append(taskScheduleModel.getBeApart()+1);cronExp.append(" ");cronExp.append("* ");cronExp.append("? ");cronExp.append("*");}else {cronExp.append("* ");cronExp.append("* ");cronExp.append("?");}}else if(taskScheduleModel.getJobType().getValue() == 3){cronExp.append("? ");cronExp.append("* ");Integer[] weeks = taskScheduleModel.getDayOfWeeks();for(int i = 0; i < weeks.length; i++){if(i == 0){cronExp.append(weeks[i]);} else{cronExp.append(",").append(weeks[i]);}}}else if(taskScheduleModel.getJobType().getValue() == 2){Integer[] days = taskScheduleModel.getDayOfMonths();for(int i = 0; i < days.length; i++){if(i == 0){if(days[i]==32){String endMouthCron="0 0 0 L * ?";return endMouthCron;}else {cronExp.append(days[i]);}} else{cronExp.append(",").append(days[i]);}}cronExp.append(" * ");cronExp.append("?");}else if(taskScheduleModel.getJobType().getValue()== 4){Integer[] days = taskScheduleModel.getDayOfMonths();if(ArrayUtil.isEmpty(days)){cronExp.append("*");}else{for(int i = 0; i < days.length; i++){if(i == 0){cronExp.append(days[i]);} else{cronExp.append(",").append(days[i]);}}}Integer[] months = taskScheduleModel.getMonths();if (ArrayUtil.isEmpty(months)) {cronExp.append(" *");}else{for (int i = 0; i < months.length; i++){Integer month = months[i];if (month > 12){throw new RuntimeException("月份数据异常: "+ Arrays.toString(months));}if(i == 0){cronExp.append(" ").append(month);}else{cronExp.append(",").append(month);}}}cronExp.append(" ?");}else if(taskScheduleModel.getJobType().getValue() == 0){cronExp.append("* ");cronExp.append("* ");cronExp.append("?");}}else {System.out.println("时或分或秒参数未配置" );}return cronExp.toString();}
生成计划的详细描述
public static String createDescription(TaskScheduleModel taskScheduleModel){StringBuffer description = new StringBuffer("");
if (null != taskScheduleModel.getSecond()&& null != taskScheduleModel.getMinute()&& null != taskScheduleModel.getHour()) {if(taskScheduleModel.getJobType().getValue() == 1){description.append("每天");description.append(taskScheduleModel.getHour()).append("时");description.append(taskScheduleModel.getMinute()).append("分");description.append(taskScheduleModel.getSecond()).append("秒");}else if(taskScheduleModel.getJobType().getValue() == 3){if(taskScheduleModel.getDayOfWeeks() != null && taskScheduleModel.getDayOfWeeks().length > 0) {String days = "";for(int i : taskScheduleModel.getDayOfWeeks()) {if(i==1){days += "周日";}else {i=i-1;days += "周" + i;}}description.append("每周的").append(days).append(" ");}if (null != taskScheduleModel.getSecond()&& null != taskScheduleModel.getMinute()&& null != taskScheduleModel.getHour()) {description.append(",");description.append(taskScheduleModel.getHour()).append("时");description.append(taskScheduleModel.getMinute()).append("分");description.append(taskScheduleModel.getSecond()).append("秒");}}else if(taskScheduleModel.getJobType().getValue() == 2){if(taskScheduleModel.getDayOfMonths() != null && taskScheduleModel.getDayOfMonths().length > 0) {String days = "";for(int i : taskScheduleModel.getDayOfMonths()) {days += i + "号";}description.append("每月的").append(days).append(" ");}description.append(taskScheduleModel.getHour()).append("时");description.append(taskScheduleModel.getMinute()).append("分");description.append(taskScheduleModel.getSecond()).append("秒");}}return description.toString();}
构建Cron表达式
public static String createLoopCronExpression(int rate, int cycle) {String cron = "";switch (rate) {case 0:// 每cycle秒执行一次cron = "0/" + cycle + " * * * * ?";break;case 1:// 每cycle分钟执行一次cron = "0 0/" + cycle + " * * * ?";break;case 2:// 每cycle小时执行一次cron = "0 0 0/" + cycle + " * * ?";break;case 3:// 每cycle天的0点执行一次cron = "0 0 0 1/" + cycle + " * ?";break;case 4:// 每cycle月的1号0点执行一次cron = "0 0 0 1 1/" + cycle + " ? ";break;case 5:// 每天cycle点执行一次cron = "0 0 " + cycle+ " * * ?";break;default:// 默认每cycle秒执行一次cron = "0/1 * * * * ?";break;}return cron;}
枚举类
public enum JobEnum {EVERY("每天",0),DAY("日",1),MONTH("月",2),WEEK("周",3),YEAR("年",4),;JobEnum(String name,Integer value) {this.name = name;this.value = value;}private final String name;private final Integer value;public Integer getValue() {return value;}public String getName() {return name;}}
TaskScheduleModel
public class TaskScheduleModel {JobEnum jobType;Integer[] dayOfWeeks;Integer[] dayOfMonths;Integer second;Integer minute;Integer hour;Integer[] months;Integer beApart;public Integer[] getMonths() {return months;}public void setMonths(Integer[] months) {this.months = months;}public Integer getBeApart() {return beApart;}public void setBeApart(Integer beApart) {this.beApart = beApart;}public JobEnum getJobType() {return jobType;}public void setJobType(JobEnum jobType) {this.jobType = jobType;}public Integer[] getDayOfWeeks() {return dayOfWeeks;}public void setDayOfWeeks(Integer[] dayOfWeeks) {this.dayOfWeeks = dayOfWeeks;}public Integer[] getDayOfMonths() {return dayOfMonths;}public void setDayOfMonths(Integer[] dayOfMonths) {this.dayOfMonths = dayOfMonths;}public Integer getSecond() {return second;}public void setSecond(Integer second) {this.second = second;}public Integer getMinute() {return minute;}public void setMinute(Integer minute) {this.minute = minute;}public Integer getHour() {return hour;}public void setHour(Integer hour) {this.hour = hour;}}
测试
public static void main(String[] args) {TaskScheduleModel taskScheduleModel = new TaskScheduleModel();taskScheduleModel.setJobType(JobEnum.DAY);Integer hour = 17; Integer minute = 40; Integer second = 00; taskScheduleModel.setHour(hour);taskScheduleModel.setMinute(minute);taskScheduleModel.setSecond(second);taskScheduleModel.setBeApart(1);String cropExp = createCronExpression(taskScheduleModel);System.out.println(cropExp + ":" + createDescription(taskScheduleModel));taskScheduleModel.setJobType(JobEnum.WEEK);Integer[] dayOfWeeks = new Integer[7];dayOfWeeks[0] = 1;dayOfWeeks[1] = 2;dayOfWeeks[2] = 3;dayOfWeeks[3] = 4;dayOfWeeks[4] = 5;dayOfWeeks[5] = 6;dayOfWeeks[6] = 7;taskScheduleModel.setDayOfWeeks(dayOfWeeks);cropExp = createCronExpression(taskScheduleModel);System.out.println(cropExp + ":" + createDescription(taskScheduleModel));taskScheduleModel.setJobType(JobEnum.MONTH);Integer[] dayOfMonths = new Integer[3];dayOfMonths[0] = 1;dayOfMonths[1] = 21;dayOfMonths[2] = 13;taskScheduleModel.setDayOfMonths(dayOfMonths);cropExp = createCronExpression(taskScheduleModel);System.out.println(cropExp + ":" + createDescription(taskScheduleModel));taskScheduleModel.setJobType(JobEnum.EVERY);cropExp = createCronExpression(taskScheduleModel);System.out.println(cropExp);}
0 40 17 1/2 * ? *:每天17时40分0秒
0 40 17 ? * 1,2,3,4,5,6,7:每周的周日周1周2周3周4周5周6 ,17时40分0秒
0 40 17 1,21,13 * ?:每月的1号21号13号 17时40分0秒
0 40 17 * * ?
第二种解析方式
public class DateTimeToCronUtils {public static final String YEAR = "ss mm HH dd MM ? yyyy";public static final String MONDAY = "ss mm HH ? * 1";public static final String TUESDAY = "ss mm HH ? * 2";public static final String WEDNESDAY = "ss mm HH ? * 3";public static final String THURSDAY = "ss mm HH ? * 4";public static final String FRIDAY = "ss mm HH ? * 5";public static final String SATURDAY = "ss mm HH ? * 6";public static final String SUNDAY = "ss mm HH ? * 7";public static final String EVERYDAY = "ss mm HH * * ?";public static final String INTERVAL_DAY = "0 0 0 1/param * ? ";public static final String INTERVAL_HOUR = "0 0 0/param * * ?";public static final String INTERVAL_MINUTE = "0 0/param * * * ? ";public static String formatDateByPattern(LocalDateTime date, String dateFormat) {return DateUtil.format(date, dateFormat);}public static String formatDateByPattern(Date date, String dateFormat) {SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);String formatTimeStr = null;if (date != null) {formatTimeStr = sdf.format(date);}return formatTimeStr;}public static String getCron(Date date, String dateFormat) {return formatDateByPattern(date, dateFormat);}public static String getCron(LocalDateTime date, String dateFormat) {return formatDateByPattern(date, dateFormat);}public static String getIntervalDayCron(String param) {return INTERVAL_DAY.replace("param", param);}public static String getIntervalHourCron(String param) {return INTERVAL_HOUR.replace("param", param);}public static String getIntervalMinuteCron(String param) {return INTERVAL_MINUTE.replace("param", param);}public static void main(String[] args) {Date date = new Date();String cron = getCron(date, YEAR);System.out.println("date-每年执行一次" + cron);cron = getCron(date, MONDAY);System.out.println("date-每周一执行" + cron);cron = getCron(date, EVERYDAY);System.out.println("date-每天执行" + cron);System.out.println("------------------------------");LocalDateTime localDateTime = LocalDateTime.now();cron = getCron(localDateTime, YEAR);System.out.println("localDateTime-每年执行一次" + cron);cron = getCron(localDateTime, MONDAY);System.out.println("localDateTime-每周一执行" + cron);cron = getCron(localDateTime, EVERYDAY);System.out.println("localDateTime-每天执行" + cron);LocalDate localDate = LocalDate.now();LocalDateTime dateTime = localDate.atTime(13, 14);cron = getCron(dateTime, EVERYDAY);System.out.println("localDateTime-每天指定时间执行" + cron);cron = getIntervalDayCron("1");System.out.println("localDateTime-间隔1天执行" + cron);cron = getIntervalHourCron("2");System.out.println("localDateTime-间隔2小时执行" + cron);cron = getIntervalMinuteCron("5");System.out.println("localDateTime-间隔5分钟执行" + cron);}}