Sunday, July 10, 2022

[SOLVED] @PostConstruct and @Schedule with cron

Issue

I was using the following code-snippet for a long time to trigger an export right after the application was run and as well at the provided crontab.

@PostConstruct
@Scheduled(cron = "${" + EXPORT_SCHEDULE + "}")
public void exportJob()
{
    exportService().exportTask();
}

After updating to Spring-Boot 2.6.x the policy according to "cyclic bean definition" got stricter and I couldn't use both annotations on this method anymore. Some answers recommended merging the @PostConstruct into the @Scheduled as initialDelay = 0 but crontab and the other properties of @Scheduled are not compatible. Resulting in following exception:

Caused by: java.lang.IllegalStateException: Encountered invalid @Scheduled method 'exportJob': 'initialDelay' not supported for cron triggers

Solution

A working solution I found was to use just the @Scheduled annotation but also have another method be annotated with @Scheduled and initialDelay=0 which just proxies the other method.

@Scheduled(cron = "${" + EXPORT_SCHEDULE + "}")
public void cronJob()
{
    exportService().exportTask();
}

@Scheduled(fixedRate = Integer.MAX_VALUE, initialDelay = 0)
public void exportJob()
{
    cronJob();
}

In theory, the cronJob is triggered more often, hence I chose it to do the service call. One could structure the call chain in the opposite direction as well.



Answered By - Valerij Dobler
Answer Checked By - David Goodson (WPSolving Volunteer)