Cron expression tool class CronUtil
Building Cron Expressions
/**
*
*Method Summary: Building Cron Expressions
*@param taskScheduleModel
*@return String
*/
public static String createCronExpression(TaskScheduleModel taskScheduleModel){<!-- -->
StringBuffer cronExp = new StringBuffer("");
if(null == taskScheduleModel.getJobType()) {<!-- -->
System.out.println("Execution cycle is not configured" );//Execution cycle is not configured
}
if (null != taskScheduleModel.getSecond()
& amp; & amp; null != taskScheduleModel.getMinute()
& amp; & amp; null != taskScheduleModel.getHour()) {<!-- -->
//Second
cronExp.append(taskScheduleModel.getSecond()).append(" ");
//point
cronExp.append(taskScheduleModel.getMinute()).append(" ");
//Hour
cronExp.append(taskScheduleModel.getHour()).append(" ");
//every day
if(taskScheduleModel.getJobType().getValue() == 1){<!-- -->
if(taskScheduleModel.getBeApart()!=null){<!-- -->
cronExp.append("1");//Day
cronExp.append("/");
cronExp.append(taskScheduleModel.getBeApart() + 1);//month
cronExp.append(" ");
cronExp.append("* ");
cronExp.append("? ");//week
cronExp.append("*");
}else {<!-- -->
cronExp.append("* ");//Day
cronExp.append("* ");//Month
cronExp.append("?");//week
}
}
//by week
else if(taskScheduleModel.getJobType().getValue() == 3){<!-- -->
//The day of the month
cronExp.append("? ");
//month
cronExp.append("* ");
//week
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]);
}
}
}
//by month
else if(taskScheduleModel.getJobType().getValue() == 2){<!-- -->
//What days of the month
Integer[] days = taskScheduleModel.getDayOfMonths();
for(int i = 0; i < days.length; i + + ){<!-- -->
if(i == 0){<!-- -->
if(days[i]==32){<!-- -->
//Last day of this month
String endMouthCron="0 0 0 L * ?";
return endMouthCron;
}else {<!-- -->
cronExp.append(days[i]);
}
} else{<!-- -->
cronExp.append(",").append(days[i]);
}
}
//month
cronExp.append(" * ");
//week
cronExp.append("?");
}
//by year
else if(taskScheduleModel.getJobType().getValue()== 4){<!-- -->
//Which days in a year
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]);
}
}
}
//month
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("Month data exception: " + 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("* ");//Day
cronExp.append("* ");//Month
cronExp.append("?");//week
}
}
else {<!-- -->
System.out.println("The hours, minutes, or seconds parameters are not configured" ); //The hours, minutes, or seconds parameters are not configured.
}
return cronExp.toString();
}
Detailed description of the generation plan
/**
*
*Method summary: Detailed description of the generated plan
*@param taskScheduleModel
*@return String
*/
public static String createDescription(TaskScheduleModel taskScheduleModel){<!-- -->
StringBuffer description = new StringBuffer("");
//Plan execution start time
// Date startTime = taskScheduleModel.getScheduleStartTime();
if (null != taskScheduleModel.getSecond()
& amp; & amp; null != taskScheduleModel.getMinute()
& amp; & amp; null != taskScheduleModel.getHour()) {<!-- -->
//by day
if(taskScheduleModel.getJobType().getValue() == 1){<!-- -->
description.append("every day");
description.append(taskScheduleModel.getHour()).append("hour");
description.append(taskScheduleModel.getMinute()).append("minute");
description.append(taskScheduleModel.getSecond()).append("second");
}
//by week
else if(taskScheduleModel.getJobType().getValue() == 3){<!-- -->
if(taskScheduleModel.getDayOfWeeks() != null & amp; & amp; taskScheduleModel.getDayOfWeeks().length > 0) {<!-- -->
String days = "";
for(int i : taskScheduleModel.getDayOfWeeks()) {<!-- -->
if(i==1){<!-- -->
days + = "Sunday";
}else {<!-- -->
i=i-1;
days + = "week" + i;
}
}
description.append("weekly").append(days).append(" ");
}
if (null != taskScheduleModel.getSecond()
& amp; & amp; null != taskScheduleModel.getMinute()
& amp; & amp; null != taskScheduleModel.getHour()) {<!-- -->
description.append(",");
description.append(taskScheduleModel.getHour()).append("hour");
description.append(taskScheduleModel.getMinute()).append("minute");
description.append(taskScheduleModel.getSecond()).append("second");
}
}
//by month
else if(taskScheduleModel.getJobType().getValue() == 2){<!-- -->
//select month
if(taskScheduleModel.getDayOfMonths() != null & amp; & amp; taskScheduleModel.getDayOfMonths().length > 0) {<!-- -->
String days = "";
for(int i : taskScheduleModel.getDayOfMonths()) {<!-- -->
days + = i + "number";
}
description.append("monthly").append(days).append(" ");
}
description.append(taskScheduleModel.getHour()).append("hour");
description.append(taskScheduleModel.getMinute()).append("minute");
description.append(taskScheduleModel.getSecond()).append("second");
}
}
return description.toString();
}
Building Cron Expressions
/**
* @description: Construct Cron expression
*
* @return String
* @author panlupeng
*
*/
public static String createLoopCronExpression(int rate, int cycle) {<!-- -->
String cron = "";
switch (rate) {<!-- -->
case 0:// executed once every cycle seconds
cron = "0/" + cycle + " * * * * ?";
break;
case 1:// executed once every cycle minute
cron = "0 0/" + cycle + " * * * ?";
break;
case 2:// executed once every cycle hour
cron = "0 0 0/" + cycle + " * * ?";
break;
case 3:// Execute once at 0 o'clock every cycle day
cron = "0 0 0 1/" + cycle + " * ?";
break;
case 4:// Execute once at 0:00 on the 1st of every cycle month
cron = "0 0 0 1 1/" + cycle + " ? ";
break;
case 5:// is executed once every day at cycle point
cron = "0 0 " + cycle + " * * ?";
break;
default:// executes once every cycle seconds by default
cron = "0/1 * * * * ?";
break;
}
return cron;
}
Enumeration class
public enum JobEnum {<!-- -->
EVERY("every day",0),
DAY("日",1),
MONTH("month",2),
WEEK("week",3),
YEAR("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 {<!-- -->
/**
*Selected job type:
* 0 -> every time every day
* 1 -> every day
* 2 -> Monthly
* 3 -> Weekly
* 4 -> years
*/
JobEnum jobType;
/**Which days of the week*/
Integer[] dayOfWeeks;
/**What days of the month*/
Integer[] dayOfMonths;
/**Second */
Integer second;
/**point */
Integer minute;
/**hour */
Integer hour;
/**
* Year
*/
Integer[] months;
/**
* interval
*/
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;
}
}
Test
public static void main(String[] args) {<!-- -->
//Execution time: start at 17:40:00 every day
TaskScheduleModel taskScheduleModel = new TaskScheduleModel();
taskScheduleModel.setJobType(JobEnum.DAY); //By day
Integer hour = 17; //hour
Integer minute = 40; //minute
Integer second = 00; //seconds
taskScheduleModel.setHour(hour);
taskScheduleModel.setMinute(minute);
taskScheduleModel.setSecond(second);
//Execute every few days
taskScheduleModel.setBeApart(1);
String cropExp = createCronExpression(taskScheduleModel);
System.out.println(cropExp + ":" + createDescription(taskScheduleModel));
//Execution time: 17:40:00 every day end
taskScheduleModel.setJobType(JobEnum.WEEK);//Which days of the week will it be executed?
Integer[] dayOfWeeks = new Integer[7];
dayOfWeeks[0] = 1;//Sunday
dayOfWeeks[1] = 2;//Week 1
dayOfWeeks[2] = 3;//Week 2
dayOfWeeks[3] = 4;//week 3
dayOfWeeks[4] = 5; //week 4
dayOfWeeks[5] = 6;//week 5
dayOfWeeks[6] = 7; //week 6
taskScheduleModel.setDayOfWeeks(dayOfWeeks);
cropExp = createCronExpression(taskScheduleModel);
System.out.println(cropExp + ":" + createDescription(taskScheduleModel));
taskScheduleModel.setJobType(JobEnum.MONTH);//On which days of the month will it be executed?
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);//What time does it start every day?
cropExp = createCronExpression(taskScheduleModel);
System.out.println(cropExp);
}
0 40 17 1/2 * ? *: 17:40:00 every day
0 40 17 ? * 1, 2, 3, 4, 5, 6, 7: Sunday week 1 week 2 week 3 week 4 week 5 week 6, 17 hours 40 minutes 0 seconds
0 40 17 1,21,13 * ?: 1st, 21st, 13th of every month, 17:40:00
0 40 17 * * ?
Second parsing method
/**
* @author longwei
* @Description Convert date and time to Cron expression
* @date 2022/11/4 18:17
*/
public class DateTimeToCronUtils {<!-- -->
/**
* Annual format
*/
public static final String YEAR = "ss mm HH dd MM ? yyyy";
/**
* Weekly format
*/
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";
/**
* Daily format
*/
public static final String EVERYDAY = "ss mm HH * * ?";
/**
*Interval-daily format
*/
public static final String INTERVAL_DAY = "0 0 0 1/param * ? ";
/**
* interval - hourly format
*/
public static final String INTERVAL_HOUR = "0 0 0/param * * ?";
/**
* interval - format per minute
*/
public static final String INTERVAL_MINUTE = "0 0/param * * * ? ";
/**
* LocalDateTime formatted as String
*
* @param date LocalDateTime
* @param dateFormat format format
* @return String
* @author longwei
*/
public static String formatDateByPattern(LocalDateTime date, String dateFormat) {<!-- -->
return DateUtil.format(date, dateFormat);
}
/**
* date formatted as String
*
* @param date date
* @param dateFormat format format
* @return String
* @author longwei
*/
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;
}
/**
* Time conversion Cron expression
*
* @param date date
* @param dateFormat format format
* @return Cron expression
* @author longwei
*/
public static String getCron(Date date, String dateFormat) {<!-- -->
return formatDateByPattern(date, dateFormat);
}
/**
* Time conversion Cron expression
*
* @param date date
* @param dateFormat format format
* @return Cron expression
* @author longwei
*/
public static String getCron(LocalDateTime date, String dateFormat) {<!-- -->
return formatDateByPattern(date, dateFormat);
}
/**
* Convert Cron expressions every day
*
* @param param days
* @return Cron expression
* @author longwei
*/
public static String getIntervalDayCron(String param) {<!-- -->
return INTERVAL_DAY.replace("param", param);
}
/**
* Convert Cron expression with hour interval
*
* @param param hours
* @return Cron expression
* @author longwei
*/
public static String getIntervalHourCron(String param) {<!-- -->
return INTERVAL_HOUR.replace("param", param);
}
/**
* Convert Cron expression in minutes
*
* @param param minutes
* @return Cron expression
* @author longwei
*/
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-executed once a year" + cron);
cron = getCron(date, MONDAY);
System.out.println("date-executed every Monday" + cron);
cron = getCron(date, EVERYDAY);
System.out.println("date-executed every day" + cron);
System.out.println("---------------------------------");
LocalDateTime localDateTime = LocalDateTime.now();
cron = getCron(localDateTime, YEAR);
System.out.println("localDateTime-executed once a year" + cron);
cron = getCron(localDateTime, MONDAY);
System.out.println("localDateTime-executed every Monday" + cron);
cron = getCron(localDateTime, EVERYDAY);
System.out.println("localDateTime-executed every day" + cron);
LocalDate localDate = LocalDate.now();
LocalDateTime dateTime = localDate.atTime(13, 14);
cron = getCron(dateTime, EVERYDAY);
System.out.println("localDateTime-executed at the specified time every day" + cron);
cron = getIntervalDayCron("1");
System.out.println("localDateTime-executed every 1 day" + cron);
cron = getIntervalHourCron("2");
System.out.println("localDateTime-executed every 2 hours" + cron);
cron = getIntervalMinuteCron("5");
System.out.println("localDateTime-executed every 5 minutes" + cron);
}
}