Home > Back-end >  @PostConstruct and @Schedule with cron
@PostConstruct and @Schedule with cron

Time:06-08

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

CodePudding user response:

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();
}

CodePudding user response:

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.

  • Related