search
HomeJavajavaTutorialHow Spring integrates Quartz to implement scheduled task scheduling

Recent projects need to implement scheduled execution tasks, such as regularly calculating members' points, calling third-party interfaces, etc. Since the project uses the spring framework, we will introduce it here in conjunction with the spring framework.

Writing job class

It is an ordinary pojo, as follows:

package com.pcmall.task;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
public class TaskA {
    private static Logger logger = LoggerFactory.getLogger(TaskA.class);
    public void taskA1(){
        for(int i=0;i<100;i++){
            System.out.println("----A1----" + i);
        }
    }
    public void taskA2(){
        for(int i=0;i<100;i++){
            System.out.println("----A2----" + i);
        }
    }
}

Set specific tasks in the spring configuration file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
     
    <bean id="taskA" class="com.pcmall.task.TaskA"></bean>
    <bean id="taskB" class="com.pcmall.task.TaskB"></bean>
     
    <bean id="taskJobA1" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject" ref="taskA"></property>
        <property name="targetMethod" value="taskA1"></property>
        <property name="concurrent" value="false"></property>
    </bean>
    <bean id="taskJobA2" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject" ref="taskA"></property>
        <property name="targetMethod" value="taskA2"></property>
        <property name="concurrent" value="false"></property>
    </bean>
    <bean id="taskJobB1" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject" ref="taskB"></property>
        <property name="targetMethod" value="taskB1"></property>
        <property name="concurrent" value="false"></property>
    </bean>
    <bean id="taskJobB2" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject" ref="taskB"></property>
        <property name="targetMethod" value="taskB2"></property>
        <property name="concurrent" value="false"></property>
    </bean>
     
    <bean id="taskA1Trigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
        <property name="jobDetail">
            <ref bean="taskJobA1" />
        </property>
        <property name="cronExpression">
            <value>0 0/1 * * * ?</value>
        </property>
    </bean>
    <bean id="taskA2Trigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
        <property name="jobDetail">
            <ref bean="taskJobA2" />
        </property>
        <property name="cronExpression">
            <value>0 0/2 * * * ?</value>
        </property>
    </bean>
     
    <bean id="taskB1Trigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
        <property name="jobDetail">
            <ref bean="taskJobB1" />
        </property>
        <property name="cronExpression">
            <value>0 0/1 * * * ?</value>
        </property>
    </bean>
 
    <bean id="taskB2Trigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
        <property name="jobDetail">
            <ref bean="taskJobB2" />
        </property>
        <property name="cronExpression">
            <value>0 0/2 * * * ?</value>
        </property>
    </bean>
 
    <bean id="scheduler"
        class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="taskA1Trigger" />
                <ref bean="taskA2Trigger" />
                <ref bean="taskB1Trigger" />
                <ref bean="taskB2Trigger" />
            </list>
        </property>
    </bean>
</beans>

Note

A trigger can only trigger one Job, but a Job can be triggered by multiple Triggers, which will cause concurrency problems. In Quartz, if you don't want to execute the same Job concurrently, you can implement StatefulJob instead of Job. If you use MethodInvokingJobDetailFactoryBean in Spring, you can achieve this by setting the concurrent="false" attribute.

Endnote

The benefits of using Quartz in Spring instead of a separate application include:

Putting all task scheduling settings in the same place makes tasks easier maintain.

Only encode the Job, Trigger and Scheduler can be set through configuration

You can use Pojo Java Bean to execute the job without implementing the Job interface

Detailed usage of Cron expression

Special characters allowed for field allowed values

Seconds 0-59, - * /
Minutes 0-59, - * /
Hours 0-23, - * /
Date 1-31, - * ? / L W C
Month 1-12 or JAN-DEC, - * /
Week 1-7 or SUN-SAT, - * ? / L C
#Year (can be Select) Leave blank, 1970-2099, - * /

Example:

0/5 * * * * ?: Executed every 5 seconds

"" characters are Used to specify all values. For example: "" means "every minute" in the minute field.

The "?" character is only used in date fields and weekday fields. It is used to specify "non-explicit values". This is useful when you need to specify something in one of these two fields. You will understand by looking at the example below.

The two elements of day of month and day of week are mutually exclusive. You should set a question mark to indicate that you do not want to set that field.

The "-" character is used to specify a range. For example: "10-12" in the hour domain means "10 o'clock, 11 o'clock, 12 o'clock".

The "," characters are used to specify additional values. For example: "MON, WED, FRI" means "Monday, Wednesday, Friday" in the day of the week field.

The "/" character is used to specify the increment. For example: "0/15" in the seconds field means 0, 15, 30 and 45 seconds per minute. "5/15" in the minute field means 5, 20, 35 and 50 of each hour. The symbol "" in front of "/" (such as: /10) is equivalent to 0 in front of "/" (such as: 0/10). Remember the essence: each numerical field of the expression is a set with maximum and minimum values. For example: the set of seconds field and minute field is 0-59, the date field is 1-31, and the month field is 1- 12. The character "/" can help you get the corresponding value in each character field. For example: "7/6" in the month field will only be triggered in July, not every June.

L is the omitted form of 'last', which can represent day-of-month and day-of-week fields, but has different meanings in the two fields. For example, day-of-month field represents one month. the last day. If the day-of-week field represents '7' or 'SAT', if a number is added in front of the day-of-week field, it represents the last few days of the month. For example, '6L' represents the last day of the month. A Friday.

The character "W" is only allowed in date fields. This character is used to specify the nearest working day of the date. For example: If you write "15W" in the date field, it means: the nearest working day on the 15th of this month. So, if the 15th falls on a Saturday, the task will be triggered on the 14th. If the 15th falls on a Sunday, the task will be triggered on Monday, which is the 16th. If you fill in "1W" in the date field, even if the 1st is a Saturday, the task will only be triggered on the next Monday, which is the 3rd. The most recent working day specified by the "W" character cannot span months. The character "W" can only be used with a single value and cannot be a numeric field. For example: 1-15W is wrong.

"L" and "W" can be used jointly in the date field, LW represents the working day of the last week of this month.

The character "#" is only allowed to appear in the weekday field. This character is used to specify a certain day of the month. For example: "6#3" means Friday of the third week of this month (6 means Friday, 3 means the third week). "2#1" means Monday of the first week of the month. "4#5" means Wednesday of the fifth week.

The character "C" is allowed to appear in the date field and weekday field. This character relies on a specified "calendar". That is to say, the value of this expression depends on the calculation result of the related "calendar". If there is no "calendar" associated, it is equivalent to all contained "calendars". For example, if the date field is "5C", it means the first day in the associated "calendar", or 5 days after the first day of this month. If the week field is "1C", it means the first day in the associated "calendar", or the day after the first day of the week, that is, the day after Sunday (Monday).

Expression example

"0 0 12 * * ?" 每天中午12点触发
"0 15 10 ? * *" 每天上午10:15触发
"0 15 10 * * ?" 每天上午10:15触发
"0 15 10 * * ? *" 每天上午10:15触发
"0 15 10 * * ? 2005" 2005年的每天上午10:15触发
"0 * 14 * * ?" 在每天下午2点到下午2:59期间的每1分钟触发
"0 0/5 14 * * ?" 在每天下午2点到下午2:55期间的每5分钟触发
"0 0/5 14,18 * * ?" 在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发
"0 0-5 14 * * ?" 在每天下午2点到下午2:05期间的每1分钟触发
"0 10,44 14 ? 3 WED" 每年三月的星期三的下午2:10和2:44触发
"0 15 10 ? * MON-FRI" 周一至周五的上午10:15触发
"0 15 10 15 * ?" 每月15日上午10:15触发
"0 15 10 L * ?" 每月最后一日的上午10:15触发
"0 15 10 ? * 6L" 每月的最后一个星期五上午10:15触发
"0 15 10 ? * 6L 2002-2005" 2002年至2005年的每月的最后一个星期五上午10:15触发
"0 15 10 ? * 6#3" 每月的第三个星期五上午10:15触发

The above method of Spring integrating Quartz to implement scheduled task scheduling is all the content shared by the editor. I hope it can give you a For reference, I also hope that everyone will support the PHP Chinese website.

For more articles on how Spring integrates Quartz to implement scheduled task scheduling, 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 do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I implement functional programming techniques in Java?How can I implement functional programming techniques in Java?Mar 11, 2025 pm 05:51 PM

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I use Java's NIO (New Input/Output) API for non-blocking I/O?How do I use Java's NIO (New Input/Output) API for non-blocking I/O?Mar 11, 2025 pm 05:51 PM

This article explains Java's NIO API for non-blocking I/O, using Selectors and Channels to handle multiple connections efficiently with a single thread. It details the process, benefits (scalability, performance), and potential pitfalls (complexity,

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I use Java's sockets API for network communication?How do I use Java's sockets API for network communication?Mar 11, 2025 pm 05:53 PM

This article details Java's socket API for network communication, covering client-server setup, data handling, and crucial considerations like resource management, error handling, and security. It also explores performance optimization techniques, i

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

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.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft