SpringBoot+Quartz学习实现定时任务控制Trigger的增加、激活、删除、休眠
标签(空格分隔): SpringBoot Quartz
SpringTask
SpringBoot主类加入
@EnableScheduling
注解,启用定时任务的配置
固定等待时间@Scheduled(fixedDelay = 时间间隔)
固定间隔时间@Scheduled(fixedRate = 时间间隔)
第一次执行延迟时间,配合上面两个使用@Scheduled(initialDelay = 1000 * 10,fixedDelay = 1000 * 2) Cron表达式
@Scheduled(cron = cron表达式)`
Cron表达式
s m h d M W Y(年可选)
| 字段 | 值 | 允许符号 |
|:
| 秒(s)| 0-59 | ,-*/
| 分(m)| 0-59 | ,-*/
| 时(h)| 0-23 | ,-*/
| 日(d)| 1-31 | ,-*/?LW
| 月(M)| 1-12或JAN-DEC | ,-*/
| 星期(W)| 1-7或SUN-SAT | ,-*/?L#
| 年(Y)| 1970-2099 | ,-*/
|符号 | 含义 |
|:
| * | 表示任意值 |
| ? | 只能用于d和W两个域,未说明的值 |
| - | 表示范围 |
| / | 表示频度 |
| , | 表示列出枚举值 |
| L | 表示最后,用于M和W
| W | 用于M,表示工作日,并在最近的工作日触发
| LW | 表示某月最后一个工作日
| # | 用于W域,确定这个月第几个周几
例子:
*/5 * * * * ? 每隔5秒执行一次
0 0 5-15 * * ? 每天5-15点整点触发
0 0/5 14,18 * * ? 在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发
0 0 23 L * ? 每月最后一天23点执行一次
0 15 10 ? * 6L 每月的最后一个星期五上午10:15触发
0 15 10 LW * ?" 每个月最后一个工作日的10点15分0秒触发任务
0 15 10 ? * 5#3" 每个月第三周的星期四的10点15分0秒触发任务
Spring Quartz实现定时任务
- pom.xml添加依赖
<!-- quartz -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
- 配置yml
spring:
# Quartz
quartz:
properties:
org:
quartz:
scheduler:
instanceName: myScheduler
instanceId: AUTO
jobStore:
isClustered: false
threadPool:
class: org.quartz.simpl.SimpleThreadPool
threadCount: 10
threadPriority: 5
threadsInheritContextClassLoaderOfInitializingThread: true
#job-store方式
job-store-type: jdbc
# datasource
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/etmptest?useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false&useSSL=false
username: root
password: ${dev-db-passwd}
druid:
connection-properties: config.decrypt=true;config.decrypt.key=${dev-db-passwd-publickey}
- 编写Job类
@DisallowConcurrentExecution
public class DefaultJob extends QuartzJobBean {
private static final Logger logger = LoggerFactory.getLogger(DefaultJob.class);
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
Trigger trigger = context.getTrigger();
String triggerName = trigger.getKey().getName();
logger.info("开始定时任务:{},开始时间{}", triggerName, new Date());
//Todo trigger要做什么任务
logger.info("结束定时任务:{},结束时间{}", triggerName, new Date());
}
}
- 编写Quartz工具类
@Component
@Transactional(rollbackFor = Exception.class)
public class QuartzManager {
private static final Logger logger = LoggerFactory.getLogger(QuartzManager.class);
/**
* 注入任务调度器
*/
@Autowired
private Scheduler scheduler;
//注入DefaultJob类
@Bean
public JobDetail jobDetail() {
return JobBuilder.newJob(DefaultJob.class).withIdentity("defaultJob").storeDurably().build();
}
/**
* 添加SimpleTrigger
*/
public void addSimppleTrigger(String triggerName,Date startDate, Long repeatInterval, Long repeatCount){
try {
// 触发器
TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
// 触发器名,触发器组
triggerBuilder.withIdentity(triggerName, Scheduler.DEFAULT_GROUP);
//triggerBuilder.startNow();
// 触发器时间设定
triggerBuilder.withSchedule(simpleSchedule()
.withIntervalInSeconds(repeatInterval.intValue())
.withRepeatCount(repeatCount.intValue()))
.startAt(startDate);
triggerBuilder.forJob(jobDetail());
// 创建Trigger对象
SimpleTrigger trigger = (SimpleTrigger) triggerBuilder.build();
scheduler.addJob(jobDetail(), true);
// 调度容器设置JobDetail和Trigger
scheduler.scheduleJob(trigger);
}catch (Exception e) {
logger.error("添加Simple定时器失败!", e);
throw new OccurLocationAwareException("添加Simple定时器失败!",e);
}
logger.info("添加Simple定时器成功!");
}
/**
* 添加CronTrigger
*/
public void addCronTrigger(String triggerName, String cron) {
try {
// 触发器
TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
// 触发器名,触发器组
triggerBuilder.withIdentity(triggerName, Scheduler.DEFAULT_GROUP);
triggerBuilder.startNow();
// 触发器时间设定
triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
triggerBuilder.forJob(jobDetail());
// 创建Trigger对象
CronTrigger trigger = (CronTrigger) triggerBuilder.build();
scheduler.addJob(jobDetail(), true);
// 调度容器设置JobDetail和Trigger
scheduler.scheduleJob(trigger);
} catch (Exception e) {
logger.error("添加cron定时器失败!", e);
throw new OccurLocationAwareException("添加cron定时器失败!",e);
}
logger.info("添加cron定时器成功!");
}
/**
* 暂停Trigger
*/
public void pauseTrigger(String triggerName) {
try {
logger.info("休眠定时器:" + triggerName);
TriggerKey triggerKey = new TriggerKey(triggerName, Scheduler.DEFAULT_GROUP);
//停止触发器
scheduler.pauseTrigger(triggerKey);
} catch (Exception e) {
logger.info("休眠定时器失败!");
throw new OccurLocationAwareException("休眠定时器失败!",e);
}
logger.info("休眠定时器成功!");
}
/**
* 恢复Trigger
*
* @param triggerName
* @throws Exception
*/
public void resumeTrigger(String triggerName) {
try {
logger.info("激活定时器:" + triggerName);
TriggerKey triggerKey = new TriggerKey(triggerName, Scheduler.DEFAULT_GROUP);
//重启触发器
scheduler.resumeTrigger(triggerKey);
} catch (Exception e) {
logger.info("激活定时器失败!");
throw new OccurLocationAwareException("激活定时器失败!",e);
}
logger.info("激活定时器成功!");
}
/**
* 删除Trigger
*/
public boolean removeTrigger(String triggerName) {
try {
logger.info("移除定时器:" + triggerName);
TriggerKey triggerKey = new TriggerKey(triggerName, Scheduler.DEFAULT_GROUP);
//停止触发器
scheduler.pauseTrigger(triggerKey);
//移除触发器
return scheduler.unscheduleJob(triggerKey);
} catch (Exception e) {
logger.error("移除定时器失败!", e);
throw new OccurLocationAwareException("移除定时器失败!",e);
}
}
}
- Controller调用
@RestController
@RequestMapping("/trigger")
public class TriggerController {
@Autowired
private QuartzManager manager;
/**
* @desc 添加SimpleTrigger
*/
@PostMapping("/addSimple")
public ResultBody addSimpleTrigger(@Valid @RequestBody TriggerParam triggerParam) {
manager.addSimppleTrigger(triggerParam.getTriggerName(),triggerParam.getStartDate(),triggerParam.getRepeatInterval(), triggerParam.getRepeatCount());
return new ResultBody<String>();
}
/**
* @desc 添加CronTrigger
*/
@PostMapping("/addCron")
public ResultBody addCronTrigger(@Valid @RequestBody TriggerParam triggerParam {
manager.addCronTrigger(triggerParam.getTriggerName(), triggerParam.getCronExpression());
return new ResultBody<String>();
}
/**
* @desc 激活Trigger
*/
@PostMapping("/resume")
public ResultBody resume(@Valid @RequestBody TriggerParam triggerParam) {
String triggerName = triggerParam.getTriggerName();
manager.resumeTrigger(triggerName);
return new ResultBody<String>();
}
/**
* @desc 暂停Trigger
*/
@PostMapping("/pause")
public ResultBody pause(@Valid @RequestBody TriggerParam triggerParam) {
String triggerName = triggerParam.getTriggerName();
manager.pauseTrigger(triggerName);
return new ResultBody<String>();
}
/**
* @desc 删除Trigger
*/
@PostMapping("/delete")
public ResultBody delete(@Valid @RequestBody TriggerParam triggerParam) {
String triggerName = triggerParam.getTriggerName();
manager.removeTrigger(triggerName);
return new ResultBody<String>();
}
}
如何用Quartz调用Trigger先这样,后面有时间再整理从前端到后端如何实现自定义Job和Trigger的控制