Spring Schedule — how to run in a last day of month

Raphael Rodrigues
SouJava {Rio}
Published in
1 min readApr 18, 2019

--

It’s a common use case in business requirements running a job in the last day of month.

Today’s post is regarding using Spring Boot cron expression. There are several good examples in this link:

However, if you try the code below:

/**
* At 6 pm on the last of every month
*/
@Scheduled(cron = “0 0 18 L * ?”)
public void myLastDayOfMonthJob() {
logger.debug(“last day of month”);
}

You will be surprised with the error:

java.lang.IllegalStateException: Encountered invalid @Scheduled method ‘myLastDayOfMonthJob’: For input string: “L”

A little workaround was suggested in order to solve this problem:

/**
* At 6 pm on the last 4 days of every month
* In order to discover the last day use Calendar api
*/
@Scheduled(cron = “0 0 18 28–31 * ?”)
public void myLastDayOfMonthJob() {
final Calendar c = Calendar.getInstance();
if (c.get(Calendar.DATE) == c.getActualMaximum(Calendar.DATE)) {
// do your stuff
}
}

So far so good!

--

--

Raphael Rodrigues
SouJava {Rio}

programming, data science, trading, productivity, leadership