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

原文地址:https://www.cnblogs.com/ou-pc/p/8616826.html

时间: 2024-10-08 17:33:24

java 框架-spring 整合 quartz 框架 service层 注入不了job 类的相关文章

Spring quartz Job不能依赖注入,Spring整合quartz Job任务不能注入

Spring quartz Job不能依赖注入,Spring整合quartz Job任务不能注入 Spring4整合quartz2.2.3中Job任务使用@Autowired不能注入 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ©Copyright 蕃薯耀 2017年9月6日 http://ww

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

Quartz 介绍Quartz is a full-featured, open source job scheduling service that can be integrated with, or used along side virtually any Java application - from the smallest stand-alone application to the largest e-commerce system. Quartz can be used to

Spring整合quartz框架实现任务定时调度

1.  首先需要引入需要的jar包,如上图所示. 2. 编写需要定时调度的测试类: package com.jp.task; import java.util.Date; public class TestTask{ private static int counter = 0; protected void execute() { long ms = System.currentTimeMillis(); System.out.println("\t\t" + "=====

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

spring整合quartz框架 1.创建maven工程 2.导入jar包(pom.xml) <dependencies> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.2.1</version> </dependency> <dependency&

【SSH框架】系列之 Spring 整合 Hibernate 框架

1.SSH 三大框架整合原理 Spring 与 Struts2 的整合就是将 Action 对象交给 Spring 容器来负责创建. Spring 与 Hibernate 的整合就是将 SessionFactory 交给 Spring 容器来负责维护,并且 Spring 容器负责 Session 维护以及相关的 AOP 事务. 2.Spring 整合 Hibernate 框架 (1).新建 web 项目,导入 Spring 和 Hibernate 框架所需要的 jar 包,如下图所示: (2).

spring整合shiro框架

上一篇文章已经对shiro框架做了一定的介绍,这篇文章讲述使用spring整合shiro框架,实现用户认证已经权限控制 1.搭建环境 这里不在赘述spring环境的搭建,可以简单的搭建一个ssm框架,整合后进行简单的测试 1.1 添加依赖 <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.3

Spring整合JUnit框架进行单元测试代码使用详解

[转]Spring整合JUnit框架进行单元测试代码使用详解 转自 http://blog.csdn.net/yaerfeng/article/details/25187775 感谢博主 :云淡风轻 .仅此一抹 一.Spring提供的JUnit框架扩展: 1. AbstractSpringContextTests:spring中使用spring上下文测试的Junit扩展类,我们一般不会使用这个类来进行单元测试,它是spring内部设计使用到的类    2. AbstractDependencyI

【Spring】Spring系列7之Spring整合MVC框架

7.Spring整合MVC框架 7.1.web环境中使用Spring 7.2.整合MVC框架 目标:使用Spring管理MVC的Action.Controller 最佳实践参考:http://www.itnose.net/detail/6102205.html http://wenku.baidu.com/link?url=ABQ1RvCWEAVObPpqJKWudD-UPc4YyH1MQQlu11fpCeoKexpDLxc2Lgs1c_Fh8HuqshxBfYxNfte6wU2PzdyzcSH

Spring整合Quartz定时任务 在集群、分布式系统中的应用(Mysql数据库环境)

Spring整合Quartz定时任务 在集群.分布式系统中的应用(Mysql数据库环境) 转载:http://www.cnblogs.com/jiafuwei/p/6145280.html 单个Quartz实例能给予你很好的Job调度能力,但它不能满足典型的企业需求,如可伸缩性.高可靠性满足.假如你需要故障转移的能力并能运行日益增多的 Job,Quartz集群势必成为你应用的一部分了.使用 Quartz 的集群能力可以更好的支持你的业务需求,并且即使是其中一台机器在最糟的时间崩溃了也能确保所有的