Reputation: 673
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
}
Upvotes: 0
Views: 1868
Reputation: 6936
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.
@Configuration
from DataCollector@EnableScheduling
to AppStartup DataCollector
as bean after you executed taskresult:
@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
}
Upvotes: 3