[英]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. 我有一个必须在应用程序启动时执行某些操作的应用程序,只有在启动任务完成后,我才想执行在@Scheduled注释的函数中定义的任务。 The current problem is that the task defined in the @Scheduled is executed before the one that is executed on startup.
当前的问题是@Scheduled中定义的任务在启动时先执行。
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: AppStartup.java:
@Component
public class AppStartup implements ApplicationListener<ApplicationReadyEvent> {
@Override
public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
System.out.println("On startup");
}
}
DataCollector.java: 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? 为什么不使用更长的initialDelay?
Number of milliseconds to delay before the first execution
第一次执行之前要延迟的毫秒数
like @Scheduled(fixedRate = 5000, initialDelay = 10000)
像
@Scheduled(fixedRate = 5000, initialDelay = 10000)
OR you could: register DataCollector
as bean after you executed your initial task. 或者,您可以:在执行初始任务后将
DataCollector
注册为bean。
@Configuration
from DataCollector @Configuration
@EnableScheduling
to AppStartup @EnableScheduling
移至AppStartup DataCollector
as bean after you executed task DataCollector
注册为bean 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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.