java - 如何使启动时运行的代码在计划之前首先执行?

标签 java spring spring-boot spring-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
    }

最佳答案

为什么不使用更长的初始延迟?

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
}

关于java - 如何使启动时运行的代码在计划之前首先执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56207512/

相关文章:

java - 如何显示 Spring 和 MyBatis 中的 SQL 错误?

spring - Maven 项目无法构建

java - HTTP 状态 500 - 请求处理失败 NullException

java - 为什么我的 @Autowired DataSource 和 JdbcTemplate 变为 null?

java - Spring Boot 和 Hibernate : Start an application even if a connection to the database is not available

Java - 检索文件,计算,输出到另一个文件?

java - 在 StringBuilderappend() 语句中连接所花费的执行时间是否与使用两个append() 语句不同?

spring-boot - 如何在 Spring Boot 2.6.4 中导入 spring-boot-starter-data-solr

java - 仅某些类的接口(interface)?

java - Jaxb 元素属性选择