Search code examples
javaspringspring-bootcronscheduling

@PostConstruct and @Schedule with cron


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

  • Another solution may be to implement a CommandLineRunner bean. This interface contains a run() method that is executed after the application startup

    @Bean
    CommandLineRunner cronJobRunner(CronJobService cronJobService) {
      return args ->  cronJobService.cronJob();
    }