search
HomeJavajavaTutorialSpring integrates Quartz to implement dynamic timer sample code

1. Version Description

Versions below spring 3.1 must use the quartz1.x series. Only versions above 3.1 support quartz 2.x, otherwise an error will occur.

Reason: Spring supports quartz implementation. org.springframework.scheduling.quartz.CronTriggerBean inherits org.quartz.CronTrigger. In the quartz1.x series, org.quartz.CronTrigger is a class, and in quartz2. org.quartz.CronTrigger in the Version 1.8.6

2. Add jar package

Mine is a maven project, and the relevant pom.xml configuration is as follows:

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

3. Integration implementation

1. Spring configuration

spring only needs to add the quartz scheduling factory bean

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

2. Timer work class implementation

Define the timer job class, this class Inherited from the job class

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()) + "★★★★★★★★★★★");
  }
}

Define timer management class

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

Test code, here the SchedulerFactory does not use the beans configured in spring, but is new, used for testing

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

Display results:

Spring integrates Quartz to implement dynamic timer sample codeImplementing timer management in spring Control layer code


The above is the entire content of this article, I hope it will help everyone learn It is helpful, and I hope everyone will support the PHP Chinese website.

For more sample code related articles about Spring integrating Quartz to implement dynamic timers, please pay attention to the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does platform independence benefit enterprise-level Java applications?How does platform independence benefit enterprise-level Java applications?May 03, 2025 am 12:23 AM

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?May 03, 2025 am 12:22 AM

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.May 03, 2025 am 12:21 AM

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

What are the benefits of Java's platform independence for developers?What are the benefits of Java's platform independence for developers?May 03, 2025 am 12:15 AM

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

What are the advantages of using Java for web applications that need to run on different servers?What are the advantages of using Java for web applications that need to run on different servers?May 03, 2025 am 12:13 AM

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?May 02, 2025 am 12:25 AM

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

How do newer versions of Java address platform-specific issues?How do newer versions of Java address platform-specific issues?May 02, 2025 am 12:18 AM

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

Explain the process of bytecode verification performed by the JVM.Explain the process of bytecode verification performed by the JVM.May 02, 2025 am 12:18 AM

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.