- 使用@EnableScheduling 注解定时任务,实现SchedulingConfigurer接口实现
先定义一个参数类,参数类实现从配置文件中读取参数
在resources下面定义配置文件 parameter.properties
task.cron=0 0/1 * * * ?
task.type=测试
package com.myspring.task;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource(value="classpath:parameter.properties")
@ConfigurationProperties(prefix = "task")
@Data
public class ParameterTask {
private String cron;
private String type;
}
定义定时任务类
package com.myspring.task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
@Configuration
@EnableScheduling
public class ProcessTask implements SchedulingConfigurer {
@Autowired
private ParameterTask parameterTask;
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
scheduledTaskRegistrar.addTriggerTask(
()->System.out.println("myparameter task"),new CronTrigger(parameterTask.getCron())
);
}
}
- 使用Quartz实现定时任务,首先引入Quartz集成Springboot的包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.2</version>
</dependency>
思路大概是需要一个管理类来管理job任务,包括任务的添加启动,任务执行时间的修改,任务的停止基本功能。例子比较简单,通过这个简单的离职可以扩展,实现一些复杂的功能,比如任务的注册,执行内容的修改等。
package com.myspring.quartz;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class QuartzManager {
@Autowired
private Scheduler scheduler;
private JobKey createJobKey(ScheduleParameter scheduleParameter){
return new JobKey(scheduleParameter.getJobCls().getCanonicalName());
}
/***
*
* @param scheduleParameter
*/
public void addJob(ScheduleParameter scheduleParameter) {
try {
//判断任务是否已经存在
if (!scheduler.checkExists(createJobKey(scheduleParameter))) {
// 任务名,任务组,任务执行类
JobDetail jobDetail = JobBuilder.newJob(scheduleParameter.getJobCls()).withIdentity(scheduleParameter.getJobCls().getCanonicalName()).build();
// 触发器
Trigger trigger = TriggerBuilder.newTrigger().withIdentity(scheduleParameter.getJobCls().getCanonicalName()).withSchedule(CronScheduleBuilder.cronSchedule(scheduleParameter.getCronExpression()).withMisfireHandlingInstructionDoNothing()).build();
// 调度容器设置JobDetail和Trigger
scheduler.scheduleJob(jobDetail, trigger);
// 启动
if (scheduler.isShutdown()) {
scheduler.start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param scheduleParameter
*/
public void modifyJob(ScheduleParameter scheduleParameter) {
try {
TriggerKey triggerKey = TriggerKey.triggerKey(scheduleParameter.getJobCls().getCanonicalName());
CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
if (trigger == null) {
return;
}
// 触发器
TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
// 触发器名,触发器组
triggerBuilder.withIdentity(scheduleParameter.getJobCls().getCanonicalName());
triggerBuilder.startNow();
// 触发器时间设定
triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(scheduleParameter.getCronExpression()));
// 创建Trigger对象
trigger = (CronTrigger) triggerBuilder.build();
//修改一个任务的触发时间
scheduler.rescheduleJob(triggerKey, trigger);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
*
* @param scheduleParameter
*/
public void removeJob(ScheduleParameter scheduleParameter) {
try {
TriggerKey triggerKey = TriggerKey.triggerKey(scheduleParameter.getJobCls().getCanonicalName());
// 停止触发器
scheduler.pauseTrigger(triggerKey);
// 移除触发器
scheduler.unscheduleJob(triggerKey);
// 删除任务
scheduler.deleteJob(createJobKey(scheduleParameter));
} catch (Exception e) {
e.printStackTrace();
}
}
public void shutdownJobs() {
try {
if (scheduler.isStarted()) {
scheduler.shutdown();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
这个类里面的ScheduleParameter这个类做为参数类
package com.myspring.quartz;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.quartz.CronExpression;
import org.quartz.Job;
@Getter
@Setter
public class ScheduleParameter {
private Class<? extends Job> clsJob;
private CronExpression cronExpression;
public ScheduleParameter(Class<? extends Job> clsJob, CronExpression cronExpression){
this.clsJob=clsJob;
this.cronExpression=cronExpression;
}
public Class<? extends Job> getJobCls(){
return this.clsJob;
}
public CronExpression getCronExpression() {
return cronExpression;
}
}
定义一个简单的job类用来测试
package com.myspring.quartz;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;
@Component
public class MyJob implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println(this.getClass().getCanonicalName());
}
}
定义一个请求方法来测试添加一个任务
package com.myspring.controller;
import com.myspring.dao.StudentMapper;
import com.myspring.pojo.Student;
import com.myspring.quartz.MyJob;
import com.myspring.quartz.QuartzManager;
import com.myspring.quartz.ScheduleParameter;
import org.quartz.CronExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.text.ParseException;
import java.util.List;
@RestController
public class TestController {
//
@Autowired
private StudentMapper studentMapper;
@Autowired
private QuartzManager quartzManager;
@GetMapping("/msg")
public String getMsg(){
// List<Student> list;
// list = studentMapper.queryStudents();
// System.out.println(list.get(0).toString());
CronExpression cronExpression= null;
try {
cronExpression = new CronExpression("0 0/1 * * * ?");
} catch (ParseException e) {
e.printStackTrace();
}
ScheduleParameter scheduleParameter=new ScheduleParameter(MyJob.class,cronExpression);
quartzManager.addJob(scheduleParameter);
return "message";
}
}
@EnableScheduling 实现的定时任务,更适合简单的任务。Quartz实现的定时任务,对任务进行管理,如果需要配置SchedulerFactoryBean 还可以使用@bean的方式对默认的参数进行调整。