springboot集成任务调度框架Quartz

首先

搭建一个springboot项目

然后, pom文件加上依赖

        
        
            org.quartz-scheduler
            quartz
            2.3.0
        
        
            org.springframework
            spring-context-support
        
        

创建SchedulerConfig配置类,注入Scheduler

package com.springboot.service.job;

import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

/**
 * @author Administrator
 */
@Configuration
@Component
public class SchedulerConfig {

    private static final Logger logger = LoggerFactory.getLogger(SchedulerConfig.class);


    /**
     * 初始注入scheduler
     * @return
     * @throws SchedulerException
     */
    @Bean
    public Scheduler scheduler() throws SchedulerException{
        SchedulerFactory schedulerFactoryBean = new StdSchedulerFactory();
        return schedulerFactoryBean.getScheduler();
    }

}

创建业务逻辑Job, 要实现Job接口,该类为执行业务逻辑的地方

package com.springboot.service.job;


import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TestQuartzJob implements Job {

    private static final Logger logger = LoggerFactory.getLogger(TestQuartzJob.class);

    /**
     * 执行业务逻辑的地方
     * @param jobExecutionContext
     */
    @Override
    public void execute(JobExecutionContext jobExecutionContext){
        String jobName = (String) jobExecutionContext.getJobDetail().getJobDataMap().get("jobName");
        logger.info("当前执行的任务名称是: " + jobName);
        Thread current = Thread.currentThread();
        logger.info("QuartzJobDemo.execute 定时任务Quartz:"+current.getId()+ ",name:"+current.getName());
    }
}

创建定时任务启动类,用来启动以及关闭任务

package com.springboot.service.job;

import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class QuartzManager {
    private static final Logger logger = LoggerFactory.getLogger(QuartzManager.class);

    @Autowired
    private Scheduler scheduler;

    public void startJob() throws SchedulerException {
        startJobDemo(scheduler);
    }

    public void stopJob() {
        removeJob("job1", "group1");
    }

    private void startJobDemo(Scheduler scheduler) throws SchedulerException {
        // 通过JobBuilder构建JobDetail实例,JobDetail规定只能是实现Job接口的实例
        // JobDetail 是具体Job实例
        JobDetail jobDetail = JobBuilder.newJob(TestQuartzJob.class).withIdentity("job1", "group1").build();
        //传参数到TestQuartzJob中,供其使用
        jobDetail.getJobDataMap().put("jobName","job1");
        // 基于表达式构建触发器
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/5 * * * * ?");
        // CronTrigger表达式触发器 继承于Trigger
        // TriggerBuilder 用于构建触发器实例
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("job1", "group1")
                .withSchedule(cronScheduleBuilder).build();
        //开启定时任务
        scheduler.scheduleJob(jobDetail, cronTrigger);
        //启动定时器
        scheduler.start();
    }

    /**
     * 删除定时任务
     * @param jobName
     * @param groupName
     */
    public void removeJob(String jobName, String groupName) {
        TriggerKey triggerKey = TriggerKey.triggerKey(jobName, groupName);
        try {
            if (checkExists(jobName, groupName)) {
                logger.info("开始关闭任务job1");
                //暂停触发器
                scheduler.pauseTrigger(triggerKey);
                //关闭触发器
                scheduler.unscheduleJob(triggerKey);
                logger.info("关闭任务job1成功");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 判断任务是否存在
     * @param jobName
     * @param groupName
     * @return
     * @throws SchedulerException
     */
    public boolean checkExists(String jobName, String groupName) throws SchedulerException {
        TriggerKey triggerKey = TriggerKey.triggerKey(jobName, groupName);
        return scheduler.checkExists(triggerKey);
    }

}

创建Controller测试类, 测试定时调度任务

package com.springboot.controller;

import com.springboot.service.job.QuartzManager;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class JobController {
    @Autowired
    private QuartzManager quartzManager;

    @GetMapping("start/job1")
    public void startJob1() {
        try {
            quartzManager.startJob();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
    @GetMapping("stop/job1")
    public void stopJob1() {
        quartzManager.stopJob();
    }

}

利用Postman调接口测试

开启任务

springboot集成任务调度框架Quartz_第1张图片
springboot集成任务调度框架Quartz_第2张图片
定时任务五秒执行一次

关闭任务

springboot集成任务调度框架Quartz_第3张图片
springboot集成任务调度框架Quartz_第4张图片
关闭后, 任务不在执行

你可能感兴趣的:(java,spring)