如何使启动时 运行 的代码在预定之前首先执行?

How to make a code that is run on startup execute first, before scheduled?

我有一个应用程序必须在应用程序启动时执行某些操作,只有在启动任务完成后,我想执行在带有 @Scheduled 注释的函数中定义的任务。 当前的问题是@Scheduled 中定义的任务在启动时执行的任务之前执行。

我通过插入达到了预期的效果:

Thread.sleep(100);

但是,我发现它充其量只是一个幼稚的解决方案,我想知道是否有解决此问题的优雅解决方案。

AppStartup.java:

@Component
public class AppStartup implements ApplicationListener<ApplicationReadyEvent> {

    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        System.out.println("On startup");
    }
}

DataCollector.java:

@Configuration
@EnableScheduling
public class DataCollector {

    @Scheduled(fixedRate = 5000)
    public void executeTask() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // do sth
    }

为什么不使用更长的 initialDelay?

Number of milliseconds to delay before the first execution

喜欢@Scheduled(fixedRate = 5000, initialDelay = 10000)


或者您可以:在执行初始任务后将 DataCollector 注册为 bean。

  • 从 DataCollector
  • 中删除 @Configuration
  • @EnableScheduling 移动到 AppStartup
  • 在执行任务后将DataCollector注册为bean

结果:

@Component

public class AppStartup implements ApplicationListener<ApplicationReadyEvent> {

    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        System.out.println("On startup");
        /* task execution */

        // register DataCollector
        applicationReadyEvent
             .getApplicationContext()
             .getBeanFactory()
             .createBean(DataCollector.class);
    }
}


public class DataCollector {

    @Scheduled(fixedRate = 5000)
    public void executeTask() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // do sth
}