如果其中一个调度程序运行时间更长,则Spring启动应用程序调度程序将不起作用



如果任何一个调度器需要时间来执行进程,那么我在spring-boot应用程序中有调度器,其余的调度器在给定时间或特定时间间隔后将无法工作。

@Component
public class ScheduledTask(){
@Scheduled(cron ="0 00 01 1/1 * ? ")
public void method1(){
//process 1 do something.
}
@Scheduled(initialDelay =5000, fixedRate=900000)
public void method2(){
//process 2 do something.
}
@Scheduled(cron ="0 10 00 1/1 * ? ")
public void method3(){
//process 3 do something.
}
@Scheduled(cron ="0 10 00 1/1 * ? ")
public void method4(){
//process 4 do something.
}
@Scheduled(initialDelay =5000, fixedRate=900000)
public void method5(){
//process 5 do something.
}

}

解释:方法5&方法2每15分钟运行一次。但假设我的方法5需要处理更长的时间,那么我的调度器(方法2(在接下来的15分钟内不会启动。如果我的方法5处理的时间太长,如果方法1、方法3和方法4的调度程序的时间到了(例如1A.M(,也是一样的,但这个调度程序在那个时候仍然不会运行。

请让我知道该怎么做调度器才能完美运行,而不会出现任何故障。

默认情况下,Spring Boot上下文中的调度器是单线程的。当您需要运行并行任务时,可以使用@Configuration类来实现SchedulingConfigurer接口。这允许访问基础ScheduledTaskRegistrar实例。例如,以下示例演示了如何自定义要执行的Executor并行安排任务。

@Configuration
@EnableScheduling
public class AppConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(taskExecutor());
}
@Bean(destroyMethod="shutdown")
public Executor taskExecutor() {
return Executors.newScheduledThreadPool(100);
}
}

请阅读:https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/scheduling/annotation/EnableScheduling.html

最新更新