`
lfwer
  • 浏览: 86431 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

springboot @Scheduled 并行(多线程)配置

 
阅读更多

SpringBoot自带的Scheduled,可以将它看成一个轻量级的Quartz,默认情况下是单线程的,也就是无论同时有多少个任务需要执行,都需要排队等待某个任务完成之后才能继续下一个任务。下面两种方式可以配置为并行方式:

 

方法1:通过xml配置任务线程池,然后注册到springboot容器。

 

xml配置,命名为 applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:task="http://www.springframework.org/schema/task"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/task
        http://www.springframework.org/schema/task/spring-task.xsd">

	<!-- Enables the Spring Task @Scheduled programming model -->
	<task:executor id="executor" pool-size="5" />
	<task:scheduler id="scheduler" pool-size="10" />
	<task:annotation-driven executor="executor"
		scheduler="scheduler" />

</beans>

 

注册

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

@Configuration
@ImportResource("applicationContext.xml")
public class XmlImportingConfiguration {

}

 

 

方法2:继承SchedulingConfigurer类并重写其方法即可,如下

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

 

 

最后别忘了app.java 中加入 @EnableScheduling 注解。

 

 

方法1亲测可用,源自 https://blog.csdn.net/shuist_king/article/details/69396756

方法2还未尝试过,源自 https://www.cnblogs.com/slimer/p/6222485.html

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics