@postConstruct和@schedule with cron

发布于 2025-02-05 10:34:22 字数 572 浏览 3 评论 0 原文

在运行该应用程序后,我使用以下代码 - 刺管很长一段时间来触发导出。

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

在更新了Spring-boot 2.6.x之后,根据“循环bean定义”的策略变得更加严格,我再也无法对此方法使用两种注释。一些答案建议将@postConstruct合并到@scheduled中,为 initiaLdelay = 0 ,但是crontab和@scheduled的其他属性不兼容。导致以下例外:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

关于从前 2025-02-12 10:34:22

另一个解决方案可能是实现A bean。该界面包含 run()方法,该方法是在应用程序启动之后执行的

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

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();
}
寒江雪… 2025-02-12 10:34:22

我发现的一个工作解决方案是仅使用@scheduled注释,但也有另一种方法是用@scheduled和 initiaLdelay = 0 注释的方法,它只是代理另一种方法。

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

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

从理论上讲,cronjob被更频繁地触发,因此我选择了进行服务呼叫。一个人也可以朝相反的方向构建呼叫链。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文