spring boot+quartz实现定时任务管理
时间: 2023-09-11 15:12:03 浏览: 167
使用Spring Boot和Quartz实现定时任务管理,可以让你更方便地管理和监控你的定时任务。下面是一个使用Spring Boot、Quartz和Spring MVC实现定时任务管理的示例:
首先,在你的Spring Boot应用程序中添加Quartz和Spring MVC的依赖项:
```xml
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
```
然后,在你的Spring Boot应用程序中创建一个Quartz的调度器,并添加一个Spring MVC的Controller来管理定时任务:
```java
@Configuration
public class QuartzConfig {
@Bean
public SchedulerFactoryBean schedulerFactoryBean() {
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
schedulerFactoryBean.setTriggers(myTaskTrigger().getObject());
return schedulerFactoryBean;
}
@Bean
public JobDetailFactoryBean myTaskJob() {
JobDetailFactoryBean jobDetailFactoryBean = new JobDetailFactoryBean();
jobDetailFactoryBean.setJobClass(MyTask.class);
return jobDetailFactoryBean;
}
@Bean
public CronTriggerFactoryBean myTaskTrigger() {
CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean();
cronTriggerFactoryBean.setJobDetail(myTaskJob().getObject());
cronTriggerFactoryBean.setCronExpression("0/5 * * * * ?"); // 每5秒执行一次
return cronTriggerFactoryBean;
}
}
@RestController
public class TaskController {
@Autowired
private Scheduler scheduler;
@PostMapping("/tasks")
public void addTask(@RequestBody TaskInfo taskInfo) throws SchedulerException {
JobDetail jobDetail = JobBuilder.newJob(taskInfo.getJobClass())
.withIdentity(taskInfo.getJobName(), taskInfo.getJobGroup())
.build();
CronTrigger trigger = TriggerBuilder.newTrigger()
.withIdentity(taskInfo.getTriggerName(), taskInfo.getTriggerGroup())
.withSchedule(CronScheduleBuilder.cronSchedule(taskInfo.getCronExpression()))
.build();
scheduler.scheduleJob(jobDetail, trigger);
}
@DeleteMapping("/tasks/{jobName}/{jobGroup}")
public void deleteTask(@PathVariable String jobName, @PathVariable String jobGroup) throws SchedulerException {
JobKey jobKey = new JobKey(jobName, jobGroup);
scheduler.deleteJob(jobKey);
}
}
```
在上面的代码中,我们创建了一个Spring MVC的Controller来管理定时任务。我们使用了Scheduler类来添加和删除定时任务。在添加定时任务时,我们使用了TaskInfo类来封装定时任务的信息。在删除定时任务时,我们使用了jobName和jobGroup来识别定时任务。
最后,在你的定时任务类中实现Job接口,并在类上添加@DisallowConcurrentExecution注解,以确保每个任务执行时只有一个实例:
```java
@Component
@DisallowConcurrentExecution
public class MyTask implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
// 定时任务执行的代码
}
}
```
以上就是使用Spring Boot、Quartz和Spring MVC实现定时任务管理的示例。
阅读全文