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 来进行依赖注入。

MyJobFactory

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 yunfeng
 * @version V.1.0
 * @title
 * @Desc
 * @create 2018-05-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();  
    }  


}  

声明QuartzManager,注入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 yunfeng
 * @version V.1.0
 * @title
 * @Desc
 * @create 2018-05-07 22:40
 **/

@Service
public class QuartzManager {

    @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);
        }
    }

    /**
     *
     * 功能:启动所有定时任务
     */
    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);
        }
    }
}

创建一个测试Job

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



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+"定时任务结束..");  
    }  

}  

测试添加Job实现注入

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/citask")
public class TestController {

    @Autowired
    QuartzManager quartzManager;

    @RequestMapping(value = "/test")
    public String test(@RequestParam String content){
        String jobName = "动态任务调度"+content;
        String jobGroupName = "任务组名";
        String triggerName = "触发器名"+content;
        String triggerGroupName = "触发器组名";
        String time = "*/5 * * * * ?";
        quartzManager.addJob(jobName,jobGroupName,triggerName,triggerGroupName, TestJob.class,time);

        return content;
    }
}
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yunfeng482/article/details/80316790
个人分类: 定时任务
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭