search
HomeJavajavaTutorialSpring uses Quartz task scheduling timer in Java

What is Quartz task scheduling

Quartz is another open source project of the OpenSymphony open source organization in the field of Job scheduling. It can be combined with J2EE and J2SE applications or used alone. Quartz is an open source job scheduling framework written entirely in Java. Don't let the term job scheduling scare you. Even though the Quartz framework incorporates a lot of extra functionality, in its simple form you'll find that it's almost unbearably easy to use!

Actually, he still didn’t explain it clearly. Let me simply say: Quartz job scheduling can implement scheduled tasks. It can implement task schedules similar to Windows, scheduled tasks implemented by our Windows services under .Net, etc. Moreover, it is extremely simple to use when combined with the Spring framework, and it is unbearable, except that the time setting is a bit obscure... It's not important, I'll tell you the solution later.

Now there is a requirement: when a user completes an operation in our system, we reward the user with gold coins, but it is not an instant recharge to the user. Considering performance issues, we use asynchronous or we plan to recharge the user uniformly at one o'clock in the morning. account, because there are relatively few users during this time period. what will you do?

1. Add a GoldQuartz.java file

Of course, you can do the same as me and add a cn.mayongfa.quartz Package specifically for executing scheduled tasks. kind.

The purpose of this class is to automatically add gold coins to users at regular intervals.

@Component
public class GlodQuartz {
 
 /**
  * 用户自动加金币
  * 每天凌晨一点执行一次
  */
 @Scheduled(cron = "0 0 1 * * ? ")
 public void addUserGold() {
  System.out.println("凌晨一点了,你睡了么?");
 }
 
 /**
  * 每隔5秒定时清理缓存
  */
 @Scheduled(cron = "*/5 * * * * ? ")
 public void cacheClear() {
  System.out.println("时间又过去5秒了,真令人伤感...");
 }
}

Is it done? Well, yes, it's that simple. It mainly involves what @Scheduled's cron means. I will talk about how to write it and how to automatically generate it below, because you can't understand it at all now.

2. Configure the springMVC-servlet.xml file

<!-- 扫描定时作业调度包 -->
<task:annotation-driven />
<context:component-scan base-package="cn.mayongfa.quartz"/>

It’s actually that simple and done! It's so easy to use that I can't stand it. A prerequisite for configuring this is that the beans declaration in your xml file must have:

xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
 http://www.springframework.org/schema/task
 http://www.springframework.org/schema/task/spring-task.xsd"

Run to view the results

Spring uses Quartz task scheduling timer in Java

At this point you can complete the scheduled tasks you want to perform according to your own needs. Then let me explain in detail what @Scheduled's cron means?
Cron expression includes the following 7 fields: seconds, minutes, hours, day of month, month, day of week, year (optional fields).

Cron triggers also make use of a series of special characters:

The backslash (/) character represents an increment value. For example, "5/15" in the seconds field means every 15 seconds starting at second 5.

The question mark (?) character and the letter L character are only available in the day-of-month and day-of-week fields. The question mark indicates that this field does not contain a specific value. So, if you specify a day within the month, you can insert a "?" in the day of the week field to indicate that the day of the week value does not matter. The letter L character is short for last. Put it in the date-in-month field to schedule execution on the last day of the month. In a day-of-the-week field, "L" equals "7" if present by itself, otherwise it represents the last instance of a day-of-the-week within the month. So "0L" means it is scheduled to be executed on the last Sunday of the month.

The letter (W) character in the day-of-month field schedules execution on the weekday closest to the specified value. Putting "1W" in the month date field means scheduling execution on the first working day of the month.

The pound (#) character specifies a specific working day instance for a given month. Put "MON#2" in the day-of-week field to schedule the task on the second Monday of the month.

The asterisk (*) character is a wildcard character, indicating that the field can accept any possible value.

Summary

When you need to execute some code regularly, you can use job scheduling. Quartz was born for this, and it is very convenient to combine with Spring. Quartz allows you to write code quickly. A colleague from our project team told me about it a few days ago. I used it and I was impressed by him.

For more articles related to Spring using Quartz task scheduling timer in Java, 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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use