Springboot2集成Quartz异步执行不生效

写了好几个task,我期望各个类里的task可以异步执行的,所以在类上加入了@EnableAsync注解,然而实际测试出来并没有效果,这个注解是需要加在启动类上的。
加在task类上的应该是@Async

Springboot2集成Quartz异步执行步骤

pom引入依赖:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>

启动类加上如下注解:

@SpringBootApplication
@EnableScheduling
@EnableAsync

任务类上加上如下注解:

@Component
@Async

任务类方法上加上如下注解:

@Scheduled

异步执行后踩了一个大坑

springboot的异步执行其实不是指的各个task分开执行,而是同一个task可以异步执行,异步开启后再指定Scheduled的fixedDelay或者fixedRate都是不起作用的。
springboot默认是单线程执行任务的,所以定义多个任务后会发现各个任务之间是串行执行的,如果想达到并行执行的效果,需要自定义一个线程池来跑各个任务。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

@Configuration
public class TaskExecutorConfig {

	@Bean 
	public TaskScheduler taskScheduler() { 
		ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); 
		//线程池大小 
		scheduler.setPoolSize(20); 
		//线程名字前缀 
		scheduler.setThreadNamePrefix("custom-thread-name"); 
		return scheduler; 
	}

}
  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 12
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值