spring boot中使用QuartzJobBean+SchedulingConfigurer实现动态添加定时任务
时间: 2024-03-11 17:51:44 浏览: 174
好的,下面是详细的步骤:
1. 首先,我们需要在pom.xml中添加Quartz的依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
```
2. 创建一个Job类,继承QuartzJobBean,并实现executeInternal方法。该方法就是我们要执行的任务逻辑。
```
public class MyJob extends QuartzJobBean {
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
// 任务逻辑
}
}
```
3. 创建一个实现SchedulingConfigurer接口的定时任务配置类。该类中可以动态添加定时任务,也可以从数据库、配置文件等读取定时任务。
```
@Configuration
public class QuartzConfig implements SchedulingConfigurer {
@Autowired
private ApplicationContext applicationContext;
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
// 从数据库或配置文件中读取定时任务
// ...
// 动态添加定时任务
taskRegistrar.addTriggerTask(
() -> {
MyJob myJob = applicationContext.getBean(MyJob.class);
myJob.executeInternal(null);
},
triggerContext -> {
// 定时任务表达式
CronTrigger cronTrigger = new CronTrigger("0/5 * * * * ?");
return cronTrigger.nextExecutionTime(triggerContext);
}
);
}
}
```
4. 在Spring Boot主类上加上@EnableScheduling注解,启用定时任务。
```
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
这样,我们就可以使用QuartzJobBean+SchedulingConfigurer实现动态添加定时任务了。
阅读全文
相关推荐
















