cron表达式转换工具类
时间: 2023-06-30 21:05:35 浏览: 181
Cron表达式生成工具
以下是一个Java实现的cron表达式转换工具类,可以将cron表达式转换为人类可读的格式:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class CronExpressionConverter {
private static final String[] MONTHS = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
private static final String[] DAYS_OF_WEEK = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
public static String convert(String cronExpression) {
String[] cronParts = cronExpression.split(" ");
String minutes = cronParts[0];
String hours = cronParts[1];
String dayOfMonth = cronParts[2];
String month = cronParts[3];
String dayOfWeek = cronParts[4];
String year = cronParts.length == 6 ? cronParts[5] : "";
StringBuilder sb = new StringBuilder();
sb.append("At ");
// minutes
if (minutes.equals("0")) {
sb.append("the start of every hour");
} else if (minutes.equals("*/5")) {
sb.append("every five minutes past the hour");
} else {
sb.append("minute ");
sb.append(minutes);
}
sb.append(" ");
// hours
if (hours.equals("0")) {
sb.append("midnight");
} else if (hours.equals("12")) {
sb.append("noon");
} else {
sb.append("hour ");
sb.append(hours);
}
sb.append(" on ");
// day of month
if (dayOfMonth.equals("*")) {
sb.append("every day");
} else {
sb.append("the ");
sb.append(dayOfMonth);
if (dayOfMonth.endsWith("1") && !dayOfMonth.equals("11")) {
sb.append("st");
} else if (dayOfMonth.endsWith("2") && !dayOfMonth.equals("12")) {
sb.append("nd");
} else if (dayOfMonth.endsWith("3") && !dayOfMonth.equals("13")) {
sb.append("rd");
} else {
sb.append("th");
}
sb.append(" day of the month");
}
sb.append(" ");
// month
if (month.equals("*")) {
sb.append("every month");
} else {
sb.append("in ");
sb.append(MONTHS[Integer.parseInt(month) - 1]);
}
sb.append(" ");
// day of week
if (dayOfWeek.equals("*")) {
sb.append("every day of the week");
} else {
sb.append("on ");
sb.append(DAYS_OF_WEEK[Integer.parseInt(dayOfWeek)]);
}
sb.append(" ");
// year
if (!year.equals("")) {
sb.append(year);
}
return sb.toString();
}
public static void main(String[] args) {
String cronExpression = "0 12 1 */3 *";
String humanReadable = CronExpressionConverter.convert(cronExpression);
System.out.println(humanReadable);
}
}
```
该类的`convert()`方法接受一个cron表达式,返回对应的人类可读的格式。在`main()`方法中,我们演示了如何使用该工具类将cron表达式`0 12 1 */3 *`转换为人类可读的格式,输出结果为`At minute 0 hour 12 on the 1st day of every 3rd month every day of the week `。
阅读全文