java 框架-spring 整合 quartz 框架 service层 注入不了job 类

Posted 周无极

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 框架-spring 整合 quartz 框架 service层 注入不了job 类相关的知识,希望对你有一定的参考价值。

    1.  spring  + quartz  启动 停止 添加job 功能 

         一 maven添加quartz  的jar   

    二 代码区    

   applicationContext.xml  导入 quartz.xml   <import resource="classpath:spring/quartz.xml"/>

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-4.0.xsd">
    
    
    <!-- 定时器 启动 停止  -->
    <bean id="startQuartzs" lazy-init="true" autowire="default" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
       <!-- 定义jobfactor是解决service层 注入不了job 里面问题 -->
      <property name="jobFactory" ref="jobFactory"></property>
      <property name="triggers">  
         <list>  
             <!-- <ref bean="cronTrigger" /> -->
         </list>  
      </property>  
    </bean>  
    <bean id="jobFactory" class="com.huateng.util.MyJobFactory"></bean>
    <bean id="quartzManager" class="com.huateng.util.QuartzManager" lazy-init="false" init-method="startJobs" >  
     <!--这个对象一定要注入,这样类才能进行管理,还有在类型要用get set方法,不然会报错。-->  
    <property name="scheduler" ref="startQuartzs" />  
    </bean>   
</beans>
quartz.xml
package com.huateng.controller;

import javax.annotation.Resource;
import javax.crypto.AEADBadTagException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.huateng.common.Constant;
import com.huateng.service.QuartzService;
import com.huateng.service.impl.MyJob;
import com.huateng.util.QuartzManager;

@Controller
public class QuartzController {
    //这个bean在spring中配置,可以直接注入
    @Resource
    private QuartzManager quartzManager;
   
    @Autowired
    private QuartzService quartzServer;
    
    
    //同步数据接口
    @RequestMapping(value="/synchroIncrement")
    @ResponseBody
    public String deleteLogFile(HttpServletRequest request,HttpServletResponse response) throws Exception {
        try {
            quartzServer.synchroIncrementQuartz();
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        
        }
        return "success";
    }
    
    
    
    //启动定时器
    @RequestMapping(value = "/startQuartz", method = {RequestMethod.GET})
    @ResponseBody
    public String testQuartz() throws Exception{
         try {
            quartzManager.addJob("test", "test", "test", "test",MyJob.class, Constant.CRONSTR);
        } catch (Exception e) {
            return "fail";
        }    
        //quartzManager.modifyJobTime("test", "test", "test", "test", "0 50 10 * * ?");    
        //quartzManager.removeJob("test", "test", "test", "test");    
        //quartzManager.shutdownJobs();
        return "success";
    }
     
    
    
    //停止定时器
    @RequestMapping(value = "/stopQuartz", method = {RequestMethod.GET})
    @ResponseBody
    public String shutDownQuartz() throws Exception{
        try {
            quartzManager.removeJob("test", "test", "test", "test");
        } catch (Exception e) {
        return "fail";
        }  
        return "success";
    }
}
QuartzController
package com.huateng.service.impl;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import com.huateng.service.HrService;
import com.huateng.service.QuartzService;
import com.huateng.util.QuartzManager;

@Service
public class MyJob implements Job{

    
    @Autowired
    private QuartzService quartzService;
    
    
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        try {
          quartzService.synchroIncrementQuartz();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

   
}
MyJob
package com.huateng.util;

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;

public class MyJobFactory extends AdaptableJobFactory {

    //这个对象Spring会帮我们自动注入进来,也属于Spring技术范畴.
    @Autowired
    private AutowireCapableBeanFactory capableBeanFactory;
    
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
        //调用父类的方法
        Object jobInstance = super.createJobInstance(bundle);
        //进行注入,这属于Spring的技术,不清楚的可以查看Spring的API.
        capableBeanFactory.autowireBean(jobInstance);
        return jobInstance;
    }
}
MyJobFactory
package com.huateng.util;

import org.apache.commons.lang.StringUtils;
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;

public class QuartzManager {

    private Scheduler scheduler;

    /**
     * @Description: 添加一个定时任务
     * 
     * @param jobName
     *            任务名
     * @param jobGroupName
     *            任务组名
     * @param triggerName
     *            触发器名
     * @param triggerGroupName
     *            触发器组名
     * @param jobClass
     *            任务
     * @param cron
     *            时间设置,参考quartz说明文档
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public void addJob(String jobName, String jobGroupName, String triggerName, String triggerGroupName, Class jobClass,
            String cron) {
        try {
            // 任务名,任务组,任务执行类
            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, jobGroupName).build();

            // 触发器
            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);
        }
    }
    
    

    /**
     * @Description: 修改一个任务的触发时间
     * 
     * @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)) {
                /** 方式一 :调用 rescheduleJob 开始 */
                // 触发器
                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);
                /** 方式一 :调用 rescheduleJob 结束 */

                /** 方式二:先删除,然后在创建一个新的Job */
                // JobDetail jobDetail =
                // scheduler.getJobDetail(JobKey.jobKey(jobName, jobGroupName));
                // Class<? extends Job> jobClass = jobDetail.getJobClass();
                // removeJob(jobName, jobGroupName, triggerName,
                // triggerGroupName);
                // addJob(jobName, jobGroupName, triggerName, triggerGroupName,
                // jobClass, cron);
                /** 方式二 :先删除,然后在创建一个新的Job */
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Description: 移除一个任务
     * 
     * @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));// 删除任务
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

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

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

    public Scheduler getScheduler() {
        return scheduler;
    }

    public void setScheduler(Scheduler scheduler) {
        this.scheduler = scheduler;
    }

    public String transCron(String time){
        String seconds = StringUtils.substringAfterLast(time, ":");
        String minute = StringUtils.substringAfter(time, ":").substring(0, 2);
        String hour = StringUtils.substringAfter(time, " ").substring(0, 2);
        String day = StringUtils.substringAfterLast(time, "-").substring(0, 2);
        String month =  StringUtils.substringAfter(time, "-").substring(0, 2);
        return seconds + " " + minute + " " + hour + " " + day + " " + month + " ?";
    }
}
QuartzManager

 2.  spring 整合 quartz  框架 service层 注入不了job 类 问题

    一.在quartz.xml  添加

<bean id="startQuartzs" lazy-init="true" autowire="default" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
       <!-- 定义jobfactor是解决service层 注入不了job 里面问题 -->
      <property name="jobFactory" ref="jobFactory"></property>
      <property name="triggers">  
         <list>  
             <!-- <ref bean="cronTrigger" /> -->
         </list>  
      </property>  
    </bean>  
    <bean id="jobFactory" class="com.huateng.util.MyJobFactory"></bean>

   二 .添加bean类

package com.huateng.util;

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;

public class MyJobFactory extends AdaptableJobFactory {

    //这个对象Spring会帮我们自动注入进来,也属于Spring技术范畴.
    @Autowired
    private AutowireCapableBeanFactory capableBeanFactory;
    
    protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
        //调用父类的方法
        Object jobInstance = super.createJobInstance(bundle);
        //进行注入,这属于Spring的技术,不清楚的可以查看Spring的API.
        capableBeanFactory.autowireBean(jobInstance);
        return jobInstance;
    }
}

 

   

 

以上是关于java 框架-spring 整合 quartz 框架 service层 注入不了job 类的主要内容,如果未能解决你的问题,请参考以下文章

Quartz 任务调度框架整合Spring使用

Spring整合Quartz实现定时任务

spring整合quartz时间任务调度框架

quartz与spring4整合的第一种方式

Spring 整合 Quartz框架(定时任务)

Spring整合Quartz框架实现定时任务跑批(Maven完整版)