SpringBoot搭配Quartz实现动态定时任务源码
时间: 2023-07-18 22:26:22 浏览: 179
好的,以下是 SpringBoot 搭配 Quartz 实现动态定时任务的源码:
1. 首先,我们需要引入 Quartz 和 SpringBoot 的依赖:
```xml
<!-- Quartz相关依赖 -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.2</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jobs</artifactId>
<version>2.3.2</version>
</dependency>
<!-- SpringBoot相关依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
```
2. 创建定时任务实体类,用于封装定时任务的信息,包括任务名称、任务组、任务类名、任务状态(是否启用)、任务表达式等:
```java
@Entity
@Table(name = "job_task")
@Data
public class JobTask implements Serializable {
private static final long serialVersionUID = 1L;
/**
* ID
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/**
* 任务名称
*/
@NotBlank(message = "任务名称不能为空")
private String name;
/**
* 任务分组
*/
@NotBlank(message = "任务分组不能为空")
private String group;
/**
* 任务类名
*/
@NotBlank(message = "任务类名不能为空")
private String className;
/**
* 任务状态,0:禁用,1:启用
*/
@NotNull(message = "任务状态不能为空")
private Integer status;
/**
* 任务表达式
*/
@NotBlank(message = "任务表达式不能为空")
private String cronExpression;
/**
* 创建时间
*/
private LocalDateTime createTime;
/**
* 最后一次修改时间
*/
private LocalDateTime updateTime;
}
```
3. 创建定时任务的服务类,用于管理定时任务的增删改查等操作,同时也需要实现 `InitializingBean` 接口,在启动应用时加载已存在的定时任务:
```java
@Service
@AllArgsConstructor
public class JobTaskService implements InitializingBean {
private final Scheduler scheduler;
private final JobTaskRepository jobTaskRepository;
/**
* 添加任务
* @param jobTask
* @return
* @throws Exception
*/
public boolean addJobTask(JobTask jobTask) throws Exception {
if (jobTask == null || StringUtils.isBlank(jobTask.getCronExpression())) {
return false;
}
if (StringUtils.isBlank(jobTask.getName()) || StringUtils.isBlank(jobTask.getClassName())) {
throw new Exception("任务名称或任务类名不能为空");
}
// 判断任务是否已存在
JobKey jobKey = JobKey.jobKey(jobTask.getName(), jobTask.getGroup());
if (scheduler.checkExists(jobKey)) {
return false;
}
// 构建任务实例
JobDetail jobDetail = JobBuilder.newJob(getClass(jobTask.getClassName()).getClass())
.withIdentity(jobTask.getName(), jobTask.getGroup())
.build();
// 构建任务触发器
CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(jobTask.getCronExpression());
CronTrigger trigger = TriggerBuilder.newTrigger()
.withIdentity(jobTask.getName(), jobTask.getGroup())
.withSchedule(cronScheduleBuilder)
.build();
// 注册任务和触发器
scheduler.scheduleJob(jobDetail, trigger);
// 如果任务状态为启用,则立即启动任务
if (jobTask.getStatus() == 1) {
scheduler.triggerJob(jobKey);
}
// 保存任务信息
jobTask.setCreateTime(LocalDateTime.now());
jobTask.setUpdateTime(LocalDateTime.now());
jobTaskRepository.save(jobTask);
return true;
}
/**
* 修改任务
* @param jobTask
* @return
* @throws Exception
*/
public boolean modifyJobTask(JobTask jobTask) throws Exception {
if (jobTask == null || StringUtils.isBlank(jobTask.getCronExpression())) {
return false;
}
if (StringUtils.isBlank(jobTask.getName()) || StringUtils.isBlank(jobTask.getClassName())) {
throw new Exception("任务名称或任务类名不能为空");
}
// 判断任务是否存在
JobKey jobKey = JobKey.jobKey(jobTask.getName(), jobTask.getGroup());
if (!scheduler.checkExists(jobKey)) {
return false;
}
// 修改任务触发器
CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(jobTask.getCronExpression());
CronTrigger newTrigger = TriggerBuilder.newTrigger()
.withIdentity(jobTask.getName(), jobTask.getGroup())
.withSchedule(cronScheduleBuilder)
.build();
scheduler.rescheduleJob(TriggerKey.triggerKey(jobTask.getName(), jobTask.getGroup()), newTrigger);
// 修改任务信息
JobTask oldJobTask = jobTaskRepository.findByNameAndGroup(jobTask.getName(), jobTask.getGroup());
oldJobTask.setClassName(jobTask.getClassName());
oldJobTask.setStatus(jobTask.getStatus());
oldJobTask.setCronExpression(jobTask.getCronExpression());
oldJobTask.setUpdateTime(LocalDateTime.now());
jobTaskRepository.save(oldJobTask);
return true;
}
/**
* 删除任务
* @param name
* @param group
* @return
* @throws Exception
*/
public boolean deleteJobTask(String name, String group) throws Exception {
JobKey jobKey = JobKey.jobKey(name, group);
if (!scheduler.checkExists(jobKey)) {
return false;
}
scheduler.deleteJob(jobKey);
jobTaskRepository.deleteByNameAndGroup(name, group);
return true;
}
/**
* 获取所有任务
* @return
*/
public List<JobTask> getAllJobTask() {
return jobTaskRepository.findAll();
}
/**
* 根据任务名称和分组获取任务信息
* @param name
* @param group
* @return
*/
public JobTask getJobTaskByNameAndGroup(String name, String group) {
return jobTaskRepository.findByNameAndGroup(name, group);
}
/**
* 获取任务类实例
* @param className
* @return
* @throws Exception
*/
private Object getClass(String className) throws Exception {
Class<?> clazz = Class.forName(className);
return clazz.newInstance();
}
/**
* 实现 InitializingBean 接口,在启动应用时加载已存在的定时任务
* @throws Exception
*/
@Override
public void afterPropertiesSet() throws Exception {
List<JobTask> jobTaskList = jobTaskRepository.findAll();
for (JobTask jobTask : jobTaskList) {
if (jobTask.getStatus() == 1) {
addJobTask(jobTask);
}
}
}
}
```
4. 创建定时任务的控制器类,用于处理新增、修改、删除等请求:
```java
@RestController
@AllArgsConstructor
@RequestMapping("/job")
public class JobTaskController {
private final JobTaskService jobTaskService;
/**
* 添加任务
* @param jobTask
* @return
* @throws Exception
*/
@PostMapping
public ResponseEntity addJobTask(@RequestBody JobTask jobTask) throws Exception {
boolean result = jobTaskService.addJobTask(jobTask);
return result ? ResponseEntity.ok("任务添加成功") : ResponseEntity.badRequest().body("任务添加失败");
}
/**
* 修改任务
* @param jobTask
* @return
* @throws Exception
*/
@PutMapping
public ResponseEntity modifyJobTask(@RequestBody JobTask jobTask) throws Exception {
boolean result = jobTaskService.modifyJobTask(jobTask);
return result ? ResponseEntity.ok("任务修改成功") : ResponseEntity.badRequest().body("任务修改失败");
}
/**
* 删除任务
* @param name
* @param group
* @return
* @throws Exception
*/
@DeleteMapping("/{name}/{group}")
public ResponseEntity deleteJobTask(@PathVariable String name, @PathVariable String group) throws Exception {
boolean result = jobTaskService.deleteJobTask(name, group);
return result ? ResponseEntity.ok("任务删除成功") : ResponseEntity.badRequest().body("任务删除失败");
}
/**
* 获取所有任务
* @return
*/
@GetMapping
public ResponseEntity getAllJobTask() {
List<JobTask> jobTaskList = jobTaskService.getAllJobTask();
return ResponseEntity.ok(jobTaskList);
}
/**
* 根据任务名称和分组获取任务信息
* @param name
* @param group
* @return
*/
@GetMapping("/{name}/{group}")
public ResponseEntity getJobTaskByNameAndGroup(@PathVariable String name, @PathVariable String group) {
JobTask jobTask = jobTaskService.getJobTaskByNameAndGroup(name, group);
return ResponseEntity.ok(jobTask);
}
}
```
5. 创建定时任务的启动类,用于启动 SpringBoot 应用:
```java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
/**
* 注册定时任务调度器
* @return
* @throws SchedulerException
*/
@Bean
public SchedulerFactoryBean schedulerFactoryBean() throws SchedulerException {
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
Properties properties = new Properties();
properties.put("org.quartz.scheduler.instanceName", "ChitGPTScheduler");
properties.put("org.quartz.threadPool.threadCount", "10");
schedulerFactoryBean.setQuartzProperties(properties);
schedulerFactoryBean.setStartupDelay(5);
return schedulerFactoryBean;
}
/**
* 注册定时任务实例
* @return
*/
@Bean
public Scheduler scheduler() {
return schedulerFactoryBean().getScheduler();
}
}
```
以上就是 SpringBoot 搭配 Quartz 实现动态定时任务的源码,希望能对您有所帮助!
阅读全文