如前所述,您必须为每个月的天数创建多个 CronExpressions,并为每个天数创建一个触发器,然后将所有触发器添加到所需的作业中。
这是我的版本:
CronExpressions 创建:
public static List<CronExpression> getCronExpressionList(int seconds, int minutes,
int hours, int dayInMonth, Month month,
DayOfWeek dayOfWeek) {
final String monthsWith30Days = Month.APR + "," + Month.JUN + ","
+ Month.SEP + "," + Month.NOV;
List<CronExpression> crons = new LinkedList<CronExpression>();
String timeString = String.format(("%s %s %s "), seconds, minutes,
hours, 0, 0, 0);
String dateString = "%s %s %s";
String cron = null;
cron = timeString + String.format(dateString, dayInMonth, "*", "?");
crons.add(new CronExpression(cron));
if (dayInMonth > 28) {
String febCron = timeString + getFebruarLastDayDateString(dateString);
crons.add(new CronExpression(febCron));
if (dayInMonth == 31) {
String monthsWithThirtyDaysCron = timeString + String.format(dateString,
"L", monthsWith30Days, "?");
crons.add(new CronExpression(monthsWithThirtyDaysCron));
}
}
return crons;
}
private static String getFebruarLastDayDateString(String initialCron)
throws ParseException {
return String.format(initialCron, "L", Month.FEB, "?");
}
请注意,我在二月的 cron 中使用了“L”,否则在闰年会出现错误。
触发器创建:
Set<CronTrigger> triggers = new HashSet<>();
int i = 1;
for (CronExpression cronEx : cronsList) {
CronTrigger trigger = newTrigger()
.withIdentity("trigger" + i, groupName)
.withSchedule(cronSchedule(cronEx))
.build();
triggers.add(trigger);
i++;
}