4

I wanted to run a spring scheduler job at 'last day of every month at 10:15' and 'First Sunday of every month' -

I have tried below - but it is giving error while initializing spring context:

org.springframework.boot.SpringApplication:Application startup failed java.lang.IllegalStateException: Encountered invalid @Scheduled method 'monthEndSchedule': For input string: "L"

@Override
@Scheduled(cron = "0 15 10 L * ?")
public void monthEndSchedule() { 
  //
}

Though below works which runs at 'every day 1 am'

@Override
@Scheduled(cron = "0 0 1 * * ?")
public void surveyDailySchedule() {
//
}

Cron expression reference I have used : http://www.quartz-scheduler.org/documentation/quartz-2.x/tutorials/crontrigger.html

Sekhar Dutta
  • 89
  • 1
  • 8

2 Answers2

6

Spring Scheduler does not support the "L" input string. So, you need to do a workaround.

First, call scheduler for each of the possible last days of months (28,29,30,31).

Then, inside the function block check with an if block whether this is the last date. If it is, then perform the expected task.

Code will be like this -

@Scheduled(cron = "0 15 10 28-31 * ?")
public void monthEndSchedule() {
    final Calendar c = Calendar.getInstance();
    if (c.get(Calendar.DATE) == c.getActualMaximum(Calendar.DATE)) {
        // do your stuff
    }
}
0

If someone prefers to do the check with JDK8+, here it is:

@Scheduled(cron = "0 15 10 28-31 * ?")
public void doStuff() {
    LocalDate date = LocalDate.now();
    LocalDate last = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());
    if (date.getDayOfMonth() == last.getDayOfMonth()) {
        //TODO: your job
    }
}

This will run at 6 pm on the last 4 days of every month.

Paulius Matulionis
  • 23,085
  • 22
  • 103
  • 143