Spring 尽管使用 CommandLineRunner,但在 Spring 应用程序加载之前触发了启动 cron 作业
Spring Boot cron job gets triggered before Spring Application is loaded in spite of using CommandLineRunner
我正在使用 Spring Boot 的 @Scheduled 注释来安排每 5 秒触发一次的 cron 作业。
cron 作业方法应该访问一些在加载 Spring 应用程序时初始化的数据。
但是,作业是在 SpringApplication.run() 完成之前触发的。如何确保仅在加载 Spring 应用程序后才触发 cron 作业?在我看来,使用 Thread.sleep() 绝对不是好的解决方案。
下面是代码片段。
MyWebApplication.java
@SpringBootApplication
@EnableScheduling
@ComponentScan(basePackages="CronJobPackage")
public class MyWebApplication implements CommandLineRunner, Runnable {
public static void main(String[] args) {
System.out.println("Starting MyWebApplication");
SpringApplication.run(MyWebApplication.class).getEnvironment().getSystemProperties();
System.out.println("Returned from MyWebApplication.run");
}
@Override
public void run(String... args) throws Exception {
initSomeData();
}
}
/********** CronJob.java **********************
@Component
public class CronJob{
@Scheduled(cron = "0/5 * * * * ?")
public void doSomething() {
//access Data here which was initialized in initSomeData()
}
}
您可以将 initData 逻辑放在 bean initDataBean 中。
之后使用@DependsOn({"initDataBean"})
。它强制 spring 在所有必需的 beans
之后创建 CronJob
看看代码:
@Component
@DependsOn({"initDataBean"})
public class CronJob {
@Scheduled(cron = "0/5 * * * * ?")
public void doSomething() {
//access Data here which was initialized in initSomeData()
}
}
我正在使用 Spring Boot 的 @Scheduled 注释来安排每 5 秒触发一次的 cron 作业。 cron 作业方法应该访问一些在加载 Spring 应用程序时初始化的数据。 但是,作业是在 SpringApplication.run() 完成之前触发的。如何确保仅在加载 Spring 应用程序后才触发 cron 作业?在我看来,使用 Thread.sleep() 绝对不是好的解决方案。 下面是代码片段。
MyWebApplication.java
@SpringBootApplication
@EnableScheduling
@ComponentScan(basePackages="CronJobPackage")
public class MyWebApplication implements CommandLineRunner, Runnable {
public static void main(String[] args) {
System.out.println("Starting MyWebApplication");
SpringApplication.run(MyWebApplication.class).getEnvironment().getSystemProperties();
System.out.println("Returned from MyWebApplication.run");
}
@Override
public void run(String... args) throws Exception {
initSomeData();
}
}
/********** CronJob.java **********************
@Component
public class CronJob{
@Scheduled(cron = "0/5 * * * * ?")
public void doSomething() {
//access Data here which was initialized in initSomeData()
}
}
您可以将 initData 逻辑放在 bean initDataBean 中。
之后使用@DependsOn({"initDataBean"})
。它强制 spring 在所有必需的 beans
CronJob
看看代码:
@Component
@DependsOn({"initDataBean"})
public class CronJob {
@Scheduled(cron = "0/5 * * * * ?")
public void doSomething() {
//access Data here which was initialized in initSomeData()
}
}