gpt4 book ai didi

java - Spring Boot中的并发调度方法

转载 作者:行者123 更新时间:2023-12-02 02:05:40 26 4
gpt4 key购买 nike

我有一个 Spring 应用程序,其中有两个用 @Component 注释的类,在每个类中,我有一个用 @Scheduled 注释的方法,这意味着我想以固定的时间间隔运行这些方法,如下所示:

这是第一个组件,它有一个 readFirstComponent() 方法,该方法从某处读取某些内容,并且需要一段时间才能执行, @成分公共(public)类 FirstComp {

@Scheduled(fixedRate = 20000 )
public void readFirstComponent() {
// body
}

//其他方法}

第二个组件几乎与第一个组件执行相同的操作,

@Component

公共(public)类 SecondComp {

@Scheduled(fixedRate = 20000 )
public void readSecondComponent() {
// body
}

//其他方法}

我有一个运行程序类来启动应用程序

@SpringBootApplication
@EnableScheduling
@ImportResource("classpath:spring/Spring-AutoScan.xml")
public class Application {
public static void main(final String args[]) {
SpringApplication.run(Application.class);
}

}

当我启动应用程序时,FirtComp 正在启动,并且 readFirstComponent() 在近 14 秒后执行完毕,然后来自 SecondComp 的 readSecondComponent() 正在启动,依此类推,我的问题是我想同时启动这两种方法,请帮我解决这个问题

最佳答案

默认情况下只有一个线程来运行调度任务。

您可以阅读 here并了解如何配置调度程序以获得具有更多线程的池。

27.4.1 Enable scheduling annotations

To enable support for @Scheduled and @Async annotations add @EnableScheduling and @EnableAsync to one of your @Configuration classes:

@Configuration
@EnableAsync
@EnableScheduling
public class AppConfig {
}

You are free to pick and choose the relevant annotations for your application. For example, if you only need support for @Scheduled, simply omit @EnableAsync. For more fine-grained control you can additionally implement the SchedulingConfigurer and/or AsyncConfigurer interfaces. See the javadocs for full details.

If you prefer XML configuration use the element.

<task:annotation-driven executor="myExecutor" scheduler="myScheduler"/>
<task:executor id="myExecutor" pool-size="5"/>
<task:scheduler id="myScheduler" pool-size="10"/>

Notice with the above XML that an executor reference is provided for handling those tasks that correspond to methods with the @Async annotation, and the scheduler reference is provided for managing those methods annotated with @Scheduled.

由于您使用注释来配置 bean,因此最好实现 SchedulingConfigurer

像这样:

@Configuration
@EnableScheduling
public class SchedulingConfig implements SchedulingConfigurer {

@Override
public void configureTasks(
ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(taskExecutor());
}

@Bean(destroyMethod = "shutdown")
public Executor taskExecutor() {
return Executors.newScheduledThreadPool(10);
}
}

关于java - Spring Boot中的并发调度方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50839243/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com