springboot quartz 创建2个 scheduler 分别配置线程池
时间: 2024-10-18 20:19:07 浏览: 22
Spring Boot和Quartz是一个流行的任务调度框架结合,它可以帮助你在Spring应用中轻松地管理定时任务。要在Spring Boot项目中创建两个Scheduler,并分别为它们配置线程池,你可以按照以下步骤操作:
1. 添加依赖:首先在你的`pom.xml`文件中添加Quartz的依赖以及Spring Boot对Quartz的支持:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
```
2. 定义两个Scheduler:在你的配置类如`AppConfig.java`中,创建两个`SchedulerFactoryBean`实例:
```java
@Configuration
public class AppConfig {
@Bean(name = "scheduler1")
public Scheduler scheduler1() {
StdSchedulerFactory factory = new StdSchedulerFactory();
ThreadPoolExecutor executor1 = new ThreadPoolExecutor(5, 10, 60L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>()); // 线程池配置1
factory.setThreadPoolExecutor(executor1);
return (Scheduler) factory.getScheduler();
}
@Bean(name = "scheduler2")
public Scheduler scheduler2() {
StdSchedulerFactory factory = new StdSchedulerFactory();
ThreadPoolExecutor executor2 = new ThreadPoolExecutor(3, 7, 30L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>()); // 线程池配置2
factory.setThreadPoolExecutor(executor2);
return (Scheduler) factory.getScheduler();
}
}
```
这里我们创建了两个线程池`executor1`和`executor2`,分别设置了不同的核心线程数、最大线程数、队列大小和超时时间。
3. 启动Scheduler:然后你需要在启动类(如`Application.java`)中启动这两个Scheduler:
```java
@SpringBootApplication
public class Application {
@Autowired
private Scheduler scheduler1;
@Autowired
private Scheduler scheduler2;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@PostConstruct
public void initSchedulers() {
try {
scheduler1.start(); // 启动第一个Scheduler
scheduler2.start(); // 启动第二个Scheduler
} catch (SchedulerException e) {
e.printStackTrace();
}
}
}
```
每个Scheduler会独立运行其对应的线程池。
阅读全文