我有一个应用程序必须在应用程序启动时执行某些操作,并且只有在启动任务完成后,我才想执行用 @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/