Workaround for CronSequenceGenerator Last day of month?
This feature is not in standard cron expression syntax. So probably Spring will never implement it. Looking at the code, I can't see any surgical solution extending CronSequenceGenerator
. So why you just don't use Quartz since it's a particular feature?
Depending on your exact need, you could implement your own Trigger. Something like:
import java.util.Date;
import org.joda.time.LocalDate;
import org.joda.time.LocalTime;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
public class LastDayOfMonthTrigger implements Trigger {
private final LocalTime time;
public LastDayOfMonthTrigger(LocalTime time) {
this.time = time;
}
@Override
public Date nextExecutionTime(TriggerContext ctx) {
Date last = ctx.lastScheduledExecutionTime();
LocalDate date = last == null ? new LocalDate() : new LocalDate(last).plusDays(1);
LocalDate lastDay = date.dayOfMonth().withMaximumValue();
return lastDay.toDateTime(time).toDate();
}
}
As a workaround I would schedule the execution for all dates
0 10 10 * * ?
and checked the actual date in the scheduled method
public void scheduledTask() {
Calendar c = Calendar.getInstance();
if (c.get(Calendar.DATE) == c.getActualMaximum(Calendar.DATE)) {
...
}
}
Optimized version which runs only on the last day of a month:
@Scheduled(cron = "0 55 23 28-31 * ?")
public void doStuffOnLastDayOfMonth() {
final Calendar c = Calendar.getInstance();
if (c.get(Calendar.DATE) == c.getActualMaximum(Calendar.DATE)) {
// do your stuff
}
}