Spring Quartz实现定时任务

Spring Quartz实现定时任务

标签(空格分隔): SpringBoot


SpringBoot Quartz实现定时任务调用一个接口

本文讲述了如何使用Quartz配置和完成一个默认Job的编写,可以操作该job的触发器,实现调用接口等定时任务。

1. pom.xml添加依赖



    org.springframework.boot
    spring-boot-starter-quartz

2. 配置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/test?useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false&useSSL=false
    username: root
    password: 123456
    druid:

3. 编写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());
    }

}

4. 编写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 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 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);
        }


    }
}
  1. 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();
    }
    
    /** 
     * @desc 添加CronTrigger
     */
    @PostMapping("/addCron")
    public ResultBody addCronTrigger(@Valid @RequestBody TriggerParam triggerParam {
            manager.addCronTrigger(triggerParam.getTriggerName(), triggerParam.getCronExpression());
        return new ResultBody();
    }
    
    /** 
     * @desc 激活Trigger
     */
    @PostMapping("/resume")
    public ResultBody resume(@Valid @RequestBody TriggerParam triggerParam) {
        String triggerName = triggerParam.getTriggerName();
        manager.resumeTrigger(triggerName);
        return new ResultBody();
    }
    
    /** 
     * @desc 暂停Trigger
     */
    @PostMapping("/pause")
    public ResultBody pause(@Valid @RequestBody TriggerParam triggerParam) {
        String triggerName = triggerParam.getTriggerName();
        manager.pauseTrigger(triggerName);
        return new ResultBody();
    }
    
    /** 
     * @desc 删除Trigger
     */
    @PostMapping("/delete")
    public ResultBody delete(@Valid @RequestBody TriggerParam triggerParam) {
        String triggerName = triggerParam.getTriggerName();
        manager.removeTrigger(triggerName);
        return new ResultBody();
    }
}

以上实现了一个默认Job,并在这个job中对触发器的一系列操作,可用于定时调用一个接口来实现定时任务,扩展的话可以用前端实现一个任务的配置和触发器的调用

你可能感兴趣的:(SpringBoot,Quartz,定时调用接口)