简体   繁体   中英

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

I have an application that has to do something on app's startup and only after a startup task has been completed, I want to execute the task that is defined in the function annotated with the @Scheduled. The current problem is that the task defined in the @Scheduled is executed before the one that is executed on startup.

I achieved the desired effect by inserting:

Thread.sleep(100);

However, I find it to be a naive solution at best, and I'm wondering if there is an elegant solution to this problem.

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
    }

why not use a longer initialDelay?

Number of milliseconds to delay before the first execution

like @Scheduled(fixedRate = 5000, initialDelay = 10000)


OR you could: register DataCollector as bean after you executed your initial task.

  • remove @Configuration from DataCollector
  • move @EnableScheduling to AppStartup
  • register DataCollector as bean after you executed task

result:

@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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM