Springboot2集成Quartz异步执行不生效

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

Springboot2集成Quartz异步执行步骤

pom引入依赖:

<dependency>
	<groupId>org.springframework.bootgroupId>
	<artifactId>spring-boot-starter-quartzartifactId>
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; 
	}

}

你可能感兴趣的:(错误汇总及解决办法,spring-boot)