这种功能直接找 AI 就行了啊
[Java] 纯文本查看 复制代码 import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class CronExpressionGenerator {
public static String generateCronExpression(int year, int month, int dayOfMonth, int hour, int minute, int second, int dayOfWeek) {
// Cron表达式支持的日期范围是1970年1月1日以后
if (year < 1970) {
throw new IllegalArgumentException("Year must be greater than or equal to 1970");
}
// 校验星期几的范围
if (dayOfWeek < 1 || dayOfWeek > 7) {
throw new IllegalArgumentException("DayOfWeek must be between 1 and 7");
}
// 将给定的时间信息转换为Date对象
Calendar calendar = Calendar.getInstance();
calendar.set(year, month - 1, dayOfMonth, hour, minute, second);
Date date = calendar.getTime();
// 使用SimpleDateFormat格式化日期,得到CRON表达式中的年月日时分秒部分
SimpleDateFormat dateFormat = new SimpleDateFormat("ss mm HH dd MM ? yyyy");
String cronExpression = dateFormat.format(date);
// 将星期几部分替换为给定的dayOfWeek
cronExpression = cronExpression.replace("?", String.valueOf(dayOfWeek));
return cronExpression;
}
public static void main(String[] args) {
// 示例:生成2023年11月15日10点30分每秒执行一次的CRON表达式
String cronExpression = generateCronExpression(2023, 11, 15, 10, 30, 0, 3); // 星期三
System.out.println(cronExpression); // 输出:0 30 10 15 11 ? 2023
}
}
[Java] 纯文本查看 复制代码 import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
public class CronExpressionValidator {
private static final List<String> ALLOWED_SPECIAL_CHARS = Arrays.asList(",", "-", "*", "/", "?", "L", "W", "#");
private static final String CRON_PATTERN = "^(\\*|(\\d+|-\\d+\\/\\d+|\\d+\\-\\d+|\\d+L|\\d+W|\\d+#\\d+)){1,5} \\*(\\*|(\\d+|-\\d+\\/\\d+|\\d+\\-\\d+|\\d+L|\\d+W|\\d+#\\d+)){1,5} \\*(\\*|(\\d+|-\\d+\\/\\d+|\\d+\\-\\d+|\\d+L|\\d+W|\\d+#\\d+)){1,5} \\*|(\\d+|-\\d+\\/\\d+|\\d+\\-\\d+|\\d+L|\\d+W|\\d+#\\d+)){1,2} \\? (\\*|(\\d+|\\d{2}))$";
public static boolean isValidCronExpression(String cronExpression) {
// 空字符串或null直接返回false
if (cronExpression == null || cronExpression.isEmpty()) {
return false;
}
// 检查每个字段的特殊字符是否合法
String[] fields = cronExpression.split(" ");
if (fields.length != 6 && fields.length != 7) {
return false;
}
for (String field : fields) {
for (char c : field.toCharArray()) {
if (!Character.isDigit(c) && !ALLOWED_SPECIAL_CHARS.contains(String.valueOf(c))) {
return false;
}
}
}
// 使用正则表达式进行校验
return Pattern.matches(CRON_PATTERN, cronExpression);
}
public static void main(String[] args) {
String validCron = "0 0 12 * * ? *";
String invalidCron = "0 0 12 * * ?";
System.out.println(validCron + ": " + isValidCronExpression(validCron));
System.out.println(invalidCron + ": " + isValidCronExpression(invalidCron));
}
} |