欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring整合Quartz实现动态定时器的示例代码

程序员文章站 2024-03-07 21:19:57
一、版本说明 spring3.1以下的版本必须使用quartz1.x系列,3.1以上的版本才支持quartz 2.x,不然会出错。 原因:spring对于quartz的...

一、版本说明

spring3.1以下的版本必须使用quartz1.x系列,3.1以上的版本才支持quartz 2.x,不然会出错。

原因:spring对于quartz的支持实现,org.springframework.scheduling.quartz.crontriggerbean继承了org.quartz.crontrigger,在quartz1.x系列中org.quartz.crontrigger是个类,而在quartz2.x系列中org.quartz.crontrigger变成了接口,从而造成无法用spring的方式配置quartz的触发器(trigger)

此示例所选版本:spring版本号3.0.7.release,quartz版本1.8.6

二、添加jar包

我的是maven工程,pom.xml相关配置如下:

 <properties>
    <project.build.sourceencoding>utf-8</project.build.sourceencoding>
    <spring.version>3.0.7.release</spring.version>
    <quartz.version>1.8.6</quartz.version>
  </properties>
     <dependency>
      <groupid>org.springframework</groupid>
      <artifactid>spring-context</artifactid>
      <version>${spring.version}</version>
      <exclusions>
        <!-- exclude commons logging in favor of slf4j -->
        <exclusion>
          <groupid>commons-logging</groupid>
          <artifactid>commons-logging</artifactid>
        </exclusion>
      </exclusions>
    </dependency>

    <dependency><!--3.0.7没这个包 -->
      <groupid>org.springframework</groupid>
      <artifactid>spring-context-support</artifactid>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupid>org.springframework</groupid>
      <artifactid>spring-webmvc</artifactid>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupid>org.springframework</groupid>
      <artifactid>spring-orm</artifactid>
      <version>${spring.version}</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupid>org.springframework</groupid>
      <artifactid>spring-test</artifactid>
      <version>${spring.version}</version>
      <type>jar</type>
      <scope>test</scope>
    </dependency>

 <dependency>
      <groupid>org.quartz-scheduler</groupid>
      <artifactid>quartz</artifactid>
      <version>${quartz.version}</version>
    </dependency>

三、整合实现

1、spring配置

spring只需要添加quartz调度工厂bean就可以了

复制代码 代码如下:

<bean id="schedulerfactorybean" class="org.springframework.scheduling.quartz.schedulerfactorybean" />

 2、定时器工作类实现

定义定时器作业类,该类继承自job类

package com.ld.nhmz.quartz;

import java.text.simpledateformat;
import java.util.date;

import org.quartz.job;
import org.quartz.jobexecutioncontext;
import org.quartz.jobexecutionexception;

/**
 * quartz示例定时器类
 * 
 * @author administrator
 * 
 */
public class quartzjobexample implements job {
  @override
  public void execute(jobexecutioncontext arg0) throws jobexecutionexception {
    system.out.println(new simpledateformat("yyyy-mm-dd hh:mm:ss").format(new date()) + "★★★★★★★★★★★");
  }
}

定义定时器管理类

package com.ld.nhmz.quartz;

import org.quartz.crontrigger;
import org.quartz.jobdetail;
import org.quartz.scheduler;

/**
 * quartz调度管理器
 * 
 * @author administrator
 * 
 */
public class quartzmanager {
  private static string job_group_name = "extjweb_jobgroup_name";
  private static string trigger_group_name = "extjweb_triggergroup_name";

  /**
   * @description: 添加一个定时任务,使用默认的任务组名,触发器名,触发器组名
   * 
   * @param sched
   *      调度器
   * 
   * @param jobname
   *      任务名
   * @param cls
   *      任务
   * @param time
   *      时间设置,参考quartz说明文档
   * 
   * @title: quartzmanager.java
   */
  public static void addjob(scheduler sched, string jobname, @suppresswarnings("rawtypes") class cls, string time) {
    try {
      jobdetail jobdetail = new jobdetail(jobname, job_group_name, cls);// 任务名,任务组,任务执行类
      // 触发器
      crontrigger trigger = new crontrigger(jobname, trigger_group_name);// 触发器名,触发器组
      trigger.setcronexpression(time);// 触发器时间设定
      sched.schedulejob(jobdetail, trigger);
      // 启动
      if (!sched.isshutdown()) {
        sched.start();
      }
    } catch (exception e) {
      throw new runtimeexception(e);
    }
  }

  /**
   * @description: 添加一个定时任务
   * 
   * @param sched
   *      调度器
   * 
   * @param jobname
   *      任务名
   * @param jobgroupname
   *      任务组名
   * @param triggername
   *      触发器名
   * @param triggergroupname
   *      触发器组名
   * @param jobclass
   *      任务
   * @param time
   *      时间设置,参考quartz说明文档
   * 
   * @title: quartzmanager.java
   */
  public static void addjob(scheduler sched, string jobname, string jobgroupname, string triggername, string triggergroupname, @suppresswarnings("rawtypes") class jobclass, string time) {
    try {
      jobdetail jobdetail = new jobdetail(jobname, jobgroupname, jobclass);// 任务名,任务组,任务执行类
      // 触发器
      crontrigger trigger = new crontrigger(triggername, triggergroupname);// 触发器名,触发器组
      trigger.setcronexpression(time);// 触发器时间设定
      sched.schedulejob(jobdetail, trigger);
    } catch (exception e) {
      throw new runtimeexception(e);
    }
  }

  /**
   * @description: 修改一个任务的触发时间(使用默认的任务组名,触发器名,触发器组名)
   * 
   * @param sched
   *      调度器
   * @param jobname
   * @param time
   * 
   * @title: quartzmanager.java
   */
  @suppresswarnings("rawtypes")
  public static void modifyjobtime(scheduler sched, string jobname, string time) {
    try {
      crontrigger trigger = (crontrigger) sched.gettrigger(jobname, trigger_group_name);
      if (trigger == null) {
        return;
      }
      string oldtime = trigger.getcronexpression();
      if (!oldtime.equalsignorecase(time)) {
        jobdetail jobdetail = sched.getjobdetail(jobname, job_group_name);
        class objjobclass = jobdetail.getjobclass();
        removejob(sched, jobname);
        addjob(sched, jobname, objjobclass, time);
      }
    } catch (exception e) {
      throw new runtimeexception(e);
    }
  }

  /**
   * @description: 修改一个任务的触发时间
   * 
   * @param sched
   *      调度器 *
   * @param sched
   *      调度器
   * @param triggername
   * @param triggergroupname
   * @param time
   * 
   * @title: quartzmanager.java
   */
  public static void modifyjobtime(scheduler sched, string triggername, string triggergroupname, string time) {
    try {
      crontrigger trigger = (crontrigger) sched.gettrigger(triggername, triggergroupname);
      if (trigger == null) {
        return;
      }
      string oldtime = trigger.getcronexpression();
      if (!oldtime.equalsignorecase(time)) {
        crontrigger ct = (crontrigger) trigger;
        // 修改时间
        ct.setcronexpression(time);
        // 重启触发器
        sched.resumetrigger(triggername, triggergroupname);
      }
    } catch (exception e) {
      throw new runtimeexception(e);
    }
  }

  /**
   * @description: 移除一个任务(使用默认的任务组名,触发器名,触发器组名)
   * 
   * @param sched
   *      调度器
   * @param jobname
   * 
   * @title: quartzmanager.java
   */
  public static void removejob(scheduler sched, string jobname) {
    try {
      sched.pausetrigger(jobname, trigger_group_name);// 停止触发器
      sched.unschedulejob(jobname, trigger_group_name);// 移除触发器
      sched.deletejob(jobname, job_group_name);// 删除任务
    } catch (exception e) {
      throw new runtimeexception(e);
    }
  }

  /**
   * @description: 移除一个任务
   * 
   * @param sched
   *      调度器
   * @param jobname
   * @param jobgroupname
   * @param triggername
   * @param triggergroupname
   * 
   * @title: quartzmanager.java
   */
  public static void removejob(scheduler sched, string jobname, string jobgroupname, string triggername, string triggergroupname) {
    try {
      sched.pausetrigger(triggername, triggergroupname);// 停止触发器
      sched.unschedulejob(triggername, triggergroupname);// 移除触发器
      sched.deletejob(jobname, jobgroupname);// 删除任务
    } catch (exception e) {
      throw new runtimeexception(e);
    }
  }

  /**
   * @description:启动所有定时任务
   * 
   * @param sched
   *      调度器
   * 
   * @title: quartzmanager.java
   */
  public static void startjobs(scheduler sched) {
    try {
      sched.start();
    } catch (exception e) {
      throw new runtimeexception(e);
    }
  }

  /**
   * @description:关闭所有定时任务
   * 
   * 
   * @param sched
   *      调度器
   * 
   * 
   * @title: quartzmanager.java
   */
  public static void shutdownjobs(scheduler sched) {
    try {
      if (!sched.isshutdown()) {
        sched.shutdown();
      }
    } catch (exception e) {
      throw new runtimeexception(e);
    }
  }
}

 测试代码,这里schedulerfactory没有使用spring中配置的bean,而是new出来的,做测试用

package com.ld.nhmz.quartz.test;

import org.junit.test;
import org.quartz.scheduler;
import org.quartz.schedulerfactory;
import org.quartz.impl.stdschedulerfactory;

import com.ld.nhmz.quartz.quartzjobexample;
import com.ld.nhmz.quartz.quartzmanager;

/**
 * @description: 测试类
 * 
 * @classname: quartztest.java
 */
public class quartztest {
  @test
  public void quartz() {
    try {
      schedulerfactory gschedulerfactory = new stdschedulerfactory();
      scheduler sche = gschedulerfactory.getscheduler();
      string job_name = "动态任务调度";
      system.out.println("【系统启动】开始(每1秒输出一次)...");
      quartzmanager.addjob(sche, job_name, quartzjobexample.class, "0/1 * * * * ?");

      thread.sleep(3000);
      system.out.println("【修改时间】开始(每2秒输出一次)...");
      quartzmanager.modifyjobtime(sche, job_name, "10/2 * * * * ?");
      thread.sleep(4000);
      system.out.println("【移除定时】开始...");
      quartzmanager.removejob(sche, job_name);
      system.out.println("【移除定时】成功");

      system.out.println("【再次添加定时任务】开始(每10秒输出一次)...");
      quartzmanager.addjob(sche, job_name, quartzjobexample.class, "*/10 * * * * ?");
      thread.sleep(30000);
      system.out.println("【移除定时】开始...");
      quartzmanager.removejob(sche, job_name);
      system.out.println("【移除定时】成功");
    } catch (exception e) {
      e.printstacktrace();
    }
  }
}

显示结果:

 Spring整合Quartz实现动态定时器的示例代码

spring control层代码中实现定时器管理

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。