Spring boot 集成Quartz,实现Job注入bean, 达到多任务调度控制

Spring boot 集成Quartz,实现Job注入bean, 达到多任务调度控制

添加Maven依赖

        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.2.1</version>
        </dependency>

        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz-jobs</artifactId>
            <version>2.2.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>

要实现Job注入bean必须使用spring-context-support

建一个MyJobFactory

然后 把其设置为SchedulerFactoryBean 的 JobFactory。其目的是因为我在具体的Job 中 需要Spring 注入一些Service。
所以我们要自定义一个jobfactory, 让其在具体job 类实例化时 使用Spring 的API 来进行依赖注入。

import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.stereotype.Component;
/**
 * @author wyl
 * @version V.1.0
 * @title
 * @Desc
 * @create 2018-08-07 22:39
 **/
@Component
public class MyJobFactory extends AdaptableJobFactory {

    @Autowired
    private AutowireCapableBeanFactory capableBeanFactory;

    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
        // 调用父类的方法    
        Object jobInstance = super.createJobInstance(bundle);
        // 进行注入    
        capableBeanFactory.autowireBean(jobInstance);
        return jobInstance;
    }
} 

QuartzConfig 声明先关联bean依赖

import org.quartz.Scheduler;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.context.annotation.Bean;  
import org.springframework.context.annotation.Configuration;  
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

@Configuration  
public class QuartzConfig {  
    @Autowired  
    private MyJobFactory myJobFactory;  

    @Bean  
    public SchedulerFactoryBean schedulerFactoryBean() {  
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();  
        schedulerFactoryBean.setJobFactory(myJobFactory);  
        System.out.println("myJobFactory:"+myJobFactory);  
        return schedulerFactoryBean;  
    }  
    @Bean  
    public Scheduler scheduler() {  
        return schedulerFactoryBean().getScheduler();  
    }  


}

声明QuartzManagerService,注入scheduler对quartz Job进行管理

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * @author wyl
 * @version V.1.0
 * @title
 * @Desc
 * @create 2018-08-07 22:40
 **/

@Service
public class QuartzManagerService {

    @Autowired
    private Scheduler scheduler;


    /**
     * 功能: 添加一个定时任务
     * 
     * @param jobName
     *            任务名
     * @param jobGroupName
     *            任务组名
     * @param triggerName
     *            触发器名
     * @param triggerGroupName
     *            触发器组名
     * @param jobClass
     *            任务的类类型 eg:TimedMassJob.class
     * @param cron
     *            时间设置 表达式,参考quartz说明文档
     * @param objects
     *            可变参数需要进行传参的值
     */
    public void addJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName, Class jobClass,
            String cron, Object... objects) {

        try {

            // 任务名,任务组,任务执行类
            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroupName).build();
            System.out.println("jobDetail.getKey:" + jobDetail.getKey());
            // 触发器
            if (objects != null) {
                for (int i = 0; i < objects.length; i++) {
                    // 该数据可以通过Job中的JobDataMap dataMap =
                    // context.getJobDetail().getJobDataMap();来进行参数传递值
                    jobDetail.getJobDataMap().put("data" + (i + 1), objects[i]);
                }
            }
            TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
            // 触发器名,触发器组
            triggerBuilder.withIdentity(triggerName, triggerGroupName);
            triggerBuilder.startNow();
            // 触发器时间设定
            triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
            // 创建Trigger对象
            CronTrigger trigger = (CronTrigger) triggerBuilder.build();
            // 调度容器设置JobDetail和Trigger
            scheduler.scheduleJob(jobDetail, trigger);
            // 启动
            if (!scheduler.isShutdown()) {
                scheduler.start();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 功能:修改一个任务的触发时间
     *
     * @param jobName
     * @param jobGroupName
     * @param triggerName
     *            触发器名
     * @param triggerGroupName
     *            触发器组名
     * @param cron
     *            时间设置,参考quartz说明文档
     */
    public void modifyJobTime(String jobName, String jobGroupName, String triggerName, String triggerGroupName,
            String cron) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            if (trigger == null) {
                return;
            }
            String oldTime = trigger.getCronExpression();
            if (!oldTime.equalsIgnoreCase(cron)) {
                // 触发器
                TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
                // 触发器名,触发器组
                triggerBuilder.withIdentity(triggerName, triggerGroupName);
                triggerBuilder.startNow();
                // 触发器时间设定
                triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
                // 创建Trigger对象
                trigger = (CronTrigger) triggerBuilder.build();
                // 方式一 :修改一个任务的触发时间
                scheduler.rescheduleJob(triggerKey, trigger);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 功能: 移除一个任务
     *
     * @param jobName
     * @param jobGroupName
     * @param triggerName
     * @param triggerGroupName
     */
    public void removeJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName) {
        try {

            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
            // 停止触发器
            scheduler.pauseTrigger(triggerKey);
            // 移除触发器
            scheduler.unscheduleJob(triggerKey);
            // 删除任务
            scheduler.deleteJob(JobKey.jobKey(jobName, jobGroupName));

            System.out.println("removeJob:" + JobKey.jobKey(jobName));

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }



    /**
     * 功能: 添加某个任务(其实就是启用某个任务)  修改某个任务 移除某个任务  暂停某个任务(中止某个任务) 启用某个任务
     *
     * @param jobName
     * @param jobGroupName
     * @param triggerName
     * @param triggerGroupName
     */

    /*暂停任务 可以启用*/
    public void pauseJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName) {
        try {


            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);

            scheduler.pauseTrigger(triggerKey);
            scheduler.pauseJob(JobKey.jobKey(jobName, jobGroupName));

            System.out.println("pauseJob:" + JobKey.jobKey(jobName));

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /*暂停后重启*/
    public void resumeJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName) {
        try {

            scheduler.resumeJob(JobKey.jobKey(jobName, jobGroupName));

            System.out.println("resumeJob:" + JobKey.jobKey(jobName));

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     *
     * 功能:启动所有定时任务
     */
    public void startJobs() {
        try {
            scheduler.start();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 功能:关闭所有定时任务
     */
    public void shutdownJobs() {
        try {
            if (!scheduler.isShutdown()) {
                scheduler.shutdown();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 功能:暂停所有定时任务 standby() start()
     */
    public void standbyJobs() {
        try {
            scheduler.standby();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
## 创建一个测试Job ##

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class TestJob implements Job {

@Autowired
private TestMapper testMapper;

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    String jobName = context.getJobDetail().getKey().toString().substring(8);
    System.out.println(jobName + "定时任务开启..");

    testMapper.test(jobName);
    System.out.println(jobName + "定时任务结束..");
}

}

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class TestMapper {

@Autowired
private DeviceService deviceService;

public void test(String jobName) {
    System.out.println("testtesttesttesttesttesttesttesttesttesttesttest" + "===============" + jobName);
}

}


## 测试添加Job实现注入 ##

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(“/citask”)
public class TestController {

@Autowired
private QuartzManagerService quartzManagerService;

/* 增加一个任务 */
@RequestMapping(value = "/addTest")
public String addTest() {
    String content = "addTestJob";
    String jobName = "动态任务调度" + content;
    String jobGroupName = "任务组名";
    String triggerName = "触发器名" + content;
    String triggerGroupName = "触发器组名";
    String cron = "*/5 * * * * ?";

    quartzManagerService.addJob(jobName, jobGroupName, triggerName, triggerGroupName, TestJob.class, cron);
    return content;
}

/**
 * 功能:修改一个任务的触发时间
 *
 * @param jobName
 * @param jobGroupName
 * @param triggerName
 *            触发器名
 * @param triggerGroupName
 *            触发器组名
 * @param cron
 *            时间设置,参考quartz说明文档
 */
@RequestMapping(value = "/updateTest")
public String updateTest() {
    String content = "addTestJob";
    String jobName = "动态任务调度" + content;
    String jobGroupName = "任务组名";
    String triggerName = "触发器名" + content;
    String triggerGroupName = "触发器组名";
    String time = "*/10 * * * * ?";

    quartzManagerService.modifyJobTime(jobName, jobGroupName, triggerName, triggerGroupName, time);

    return content;
}

/**
 * 功能: 移除一个任务
 *
 * @param jobName
 * @param jobGroupName
 * @param triggerName
 * @param triggerGroupName
 */

@RequestMapping(value = "/removeTest")
public String removeTest() {
    String content = "addTestJob";

    String jobName = "动态任务调度" + content;
    String jobGroupName = "任务组名";
    String triggerName = "触发器名" + content;
    String triggerGroupName = "触发器组名";

    quartzManagerService.removeJob(jobName, jobGroupName, triggerName, triggerGroupName);
    return content;
}
@RequestMapping(value = "/pauseJob")
public String pauseJob() {
    String content = "addTestJob";

    String jobName = "动态任务调度" + content;
    String jobGroupName = "任务组名";
    String triggerName = "触发器名" + content;
    String triggerGroupName = "触发器组名";

    quartzManagerService.pauseJob(jobName, jobGroupName, triggerName, triggerGroupName);
    return content;
}

@RequestMapping(value = "/resumeJob")
public String resumeJob() {
    String content = "addTestJob";

    String jobName = "动态任务调度" + content;
    String jobGroupName = "任务组名";
    String triggerName = "触发器名" + content;
    String triggerGroupName = "触发器组名";

    quartzManagerService.resumeJob(jobName, jobGroupName, triggerName, triggerGroupName);
    return content;
}

/* 开启所有任务 */
@RequestMapping(value = "/start")
public String startJobs() {
    quartzManagerService.startJobs();
    return null;
}

/* 关掉所有任务 关掉了就不能够重启所有的项目 */
@RequestMapping(value = "/shutdown")
public String shutdownJobs() {
    quartzManagerService.shutdownJobs();
    return null;
}

/* 中止所有作任务 */
@RequestMapping(value = "/standbyJobs")
public String standbyJobs() {
    quartzManagerService.standbyJobs();
    return null;
}

}
“`

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页