Usage instructions for Spring scheduled tasks
one. Classification
Classified from the perspective of implementation technology, there are currently three main technologies:
Java’s own java. util.Timer class, this class allows you to schedule a java.util.TimerTask task. Using this method allows your program to be executed at a certain frequency, but not at a specified time.
Use Quartz, which is a relatively powerful scheduler that allows your program to be executed at a specified time or at a certain frequency. The configuration is a bit complicated. .
The task that comes with Spring 3.0 and later can be regarded as a lightweight Quartz, and it is much simpler to use than Quartz.
In terms of inheritance methods of job classes, they can be divided into two categories:
The job class needs to inherit from a specific job class base class. For example, Quartz needs to inherit from org.springframework.scheduling.quartz.QuartzJobBean; java.util.Timer needs to inherit from java.util.TimerTask.
The job class is an ordinary java class and does not need to inherit from any base class.
Note: I personally recommend using the second method, because all classes are common classes and do not need to be treated differently in advance.
From the trigger timing of task scheduling, here are mainly the triggers used for jobs, there are mainly the following two types:
Triggers once every specified time. The corresponding trigger in Quartz is: org.springframework.scheduling.quartz.SimpleTriggerBean
Every It will be triggered once at the specified time. The corresponding scheduler in Quartz is: org.springframework.scheduling.quartz.CronTriggerBean
Note: Not every task can use these two triggers. Devices such as java.util.TimerTask tasks can only use the first one. Both Quartz and spring task can support these two trigger conditions.
two. Usage instructions
Introduces in detail how to use each task scheduling tool, including Quartz and spring task.
Quartz
First, the job class inherits from a specific base class: org.springframework.scheduling.quartz.QuartzJobBean.
Step 1: Define the job class
import org.quartz.JobExecutionContext;
##import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
- ##public
class Job1 extends QuartzJobBean {
- private
- int timeout;
- static
int i = 0;
//After the scheduling factory is instantiated, the scheduling starts after the timeout time -
##public
void setTimeout( - int timeout) {
##this.timeout = timeout;
}
- ##/**
* Specific tasks to be scheduled
*/
##@Override
protected void executeInternal(JobExecutionContext context)
throws JobExecutionException {
- System.out.println(
"The scheduled task is being executed...");
- }
}
- Step 2: Configure the job class JobDetailBean# in the spring configuration file
bean name="job1" class="org.springframework.scheduling.quartz.JobDetailBean"> #property name= "jobClass" value="com.gy.Job1" />
>
## entry"timeout" value="0" /> ##
mapproperty
##bean
>Description: org.springframework.scheduling.quartz.JobDetailBean has two attributes, the jobClass attribute is what we use in java For the task class defined in the code, the jobDataAsMap attribute is the attribute value that needs to be injected into the task class.
There are two types of job triggers in Quartz, namely
org .springframework.scheduling.quartz.SimpleTriggerBeanorg.springframework.scheduling.quartz.CronTriggerBean
The first SimpleTriggerBean only supports calling tasks at a certain frequency, such as running once every 30 minutes. .
The configuration method is as follows:
Xml code
bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
#property name= "jobDetail" ref="job1" />
##> - property name="cronExpression" value="0 0 12 * * ?" /> ##
- bean
>
## See the appendix for the syntax of cronExpression expression.
Xml code
"org.springframework.scheduling.quartz.SchedulerFactoryBean"> #property
> ##list
># #ref bean=
"cronTrigger"#list>
##property >
#bean>
## Description: This parameter specifies the name of the previously configured trigger. Step 5: Just start your application, that is, deploy the project to tomcat or other containers.
org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean
org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBeanThese two classes respectively correspond to the two methods of task scheduling supported by spring, namely the timer task method and the Quartz method that come with java as mentioned above. Here I only write about the usage of MethodInvokingJobDetailFactoryBean. The advantage of using this class is that our task class no longer needs to inherit from any class, but is an ordinary pojo.Step one: Write task class
Java codepublic
class Job2 {- void doJob2() {
-
System.out.println(
"Does not inherit QuartzJobBean mode - scheduling is in progress..."); }
} -
It can be seen that this is an ordinary class and has one method.
Step 2: Configure job class
- Xml code
bean id="job2"
##class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
property name="targetObject">
- ##bean class="com.gy.Job2" />
property>
##property - >
## Description: This step is a critical step, declare A MethodInvokingJobDetailFactoryBean has two key attributes: targetObject specifies the task class, and targetMethod specifies the running method. The following steps are the same as method 1. For the sake of completeness, they are also posted.
name="targetMethod" value="doJob2" />
propertyname="concurrent" value="false" />
#beanorg .springframework.scheduling.quartz.SimpleTriggerBean
org.springframework.scheduling.quartz.CronTriggerBeanThe first SimpleTriggerBean only supports calling tasks at a certain frequency, such as running once every 30 minutes. . The configuration method is as follows: Xml codebean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
#property name= "jobDetail" ref="job2" />
##> - property name="cronExpression" value="0 0 12 * * ?" /> ##
- bean
>
##You can choose any one of the above two scheduling methods according to the actual situation.
Xml code
"org.springframework.scheduling.quartz.SchedulerFactoryBean"> #property
> ##list
># #ref bean=
"cronTrigger"#list>
##property >
#bean>
##Explanation: This parameter specifies the name of the previously configured trigger. Step 5: Just start your application, that is, deploy the project to tomcat or other containers.
Spring-TaskThe previous section introduced the use of Quartz in Spring. This article introduces the self-developed scheduled task tool after Spring 3.0, spring task, which can be It is like a lightweight Quartz, and it is very simple to use. It does not require additional packages except spring-related packages, and it supports two forms of annotations and configuration files. These two will be introduced below. Way. The first one: configuration file method
The first step: write the job class
That is the ordinary pojo, as follows: Java code
import org.springframework.stereotype.Service;
@Service
public class TaskJob {
#public void job1() {
- System.out.println("Task in progress...");
- }
- }
import org.springframework.stereotype.Service;
@Service
public class TaskJob {
#public void job1() {
Step 2: Add the namespace and Description
- ##beans xmlns= "http://www.springframework.org/schema/beans" ##xmlns:task=
- "http://www.springframework.org/schema/task"
. . . . . .
-
##
xsi:schemaLocation= "http://www.springframework.org/schema/task " - >
Xml code
Maybe we don’t want to configure it in the xml file every time we write a task class. We can use the annotation @Scheduled. Let’s take a look at the source file. Definition of annotation:
Java code
@Target({java.lang.annotation.ElementType.METHOD, java.lang.annotation.ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
##@Documented
public @interface Scheduled
- {
-
public abstract String cron() ;
- ##public
abstract long fixedDelay();
- ##public
- abstract
long fixedRate();
} - It can be seen that this annotation has three methods or parameters, which respectively mean: :
Step one: Write pojo
Java code
- import org.springframework.scheduling.annotation.Scheduled;
-
##import org.springframework.stereotype.Component;
##@Component(“taskJob”)
##public class TaskJob {
##@Scheduled(cron = "0 0 3 * * ?")
# PUBLIC VOID JOB1 () {
## System.out.println ("Mission is in progress. . ”); # }
##} - # Step 2: Add task-related configuration:
Xml code
xml version="1.0" encoding="UTF-8"?>
beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
"
default-lazy-init="false">
context:annotation-config />
>
context:component-scan base-package="com.gy.mytask" />
>
task:annotation-driven scheduler="qbScheduler" mode="proxy"/>
task:scheduler id="qbScheduler" pool-size="10"/>
Note: In theory, you only need to add the configuration sentence
Ok configuration is complete. Of course, the spring task still has many parameters. I will not explain them one by one. Please refer to the xsd document for details.
Appendix: Configuration instructions for
cronExpression, please refer to Baidu google
field for specific usage and parameters. Allowed values Allowed special characters
seconds 0-59 , - * /
minutes 0-59 , - * /
Hour 0-23 , - * /
Date 1-31 , - * ? / L W C
Month 1 -12 or JAN-DEC , - * /
week 1-7 or SUN-SAT , - * ? / L C
year (Optional) Leave blank, 1970-2099, - * /
- Interval
* Wildcard
? You don’t want to set that field
The following are just a few examples
CRON expression Formula Meaning
"0 0 12 * * ?" Triggered at 12 noon every day
"0 15 10 ? * *" Every morning Triggered at 10:15
"0 15 10 * * ?" Triggered at 10:15 every morning
"0 15 10 * * ? * " Triggered every morning at 10:15
"0 15 10 * * ? 2005" Triggered every morning at 10:15 in 2005
" 0 * 14 * * ?" Triggered every minute from 2:00 pm to 2:59 every day
"0 0/5 14 * * ?" Every day from 2 pm Triggered every 5 minutes until the end of 2:55
"0 0/5 14,18 * * ?" Every day from 2 pm to 2:55 and 6 pm to 6 pm Triggered every 5 minutes in two time periods of 55 minutes
"0 0-5 14 * * ?" Triggered once every minute from 14:00 to 14:05 every day
"0 10,44 14 ? 3 WED" Triggered every Wednesday at 14:10 and 14:44 in March
"0 15 10 ? * MON-FRI" is triggered every Monday, Tuesday, Wednesday, Thursday and Friday at 10:15
The above is the detailed content of Usage instructions for Spring scheduled tasks. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use mdf files and mds files With the continuous advancement of computer technology, we can store and share data in a variety of ways. In the field of digital media, we often encounter some special file formats. In this article, we will discuss a common file format - mdf and mds files, and introduce how to use them. First, we need to understand the meaning of mdf files and mds files. mdf is the extension of the CD/DVD image file, and the mds file is the metadata file of the mdf file.

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

As an industry leader, Spring+AI provides leading solutions for various industries through its powerful, flexible API and advanced functions. In this topic, we will delve into the application examples of Spring+AI in various fields. Each case will show how Spring+AI meets specific needs, achieves goals, and extends these LESSONSLEARNED to a wider range of applications. I hope this topic can inspire you to understand and utilize the infinite possibilities of Spring+AI more deeply. The Spring framework has a history of more than 20 years in the field of software development, and it has been 10 years since the Spring Boot 1.0 version was released. Now, no one can dispute that Spring

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

After long pressing the play button of the speaker, connect to wifi in the software and you can use it. Tutorial Applicable Model: Xiaomi 12 System: EMUI11.0 Version: Xiaoai Classmate 2.4.21 Analysis 1 First find the play button of the speaker, and press and hold to enter the network distribution mode. 2 Log in to your Xiaomi account in the Xiaoai Speaker software on your phone and click to add a new Xiaoai Speaker. 3. After entering the name and password of the wifi, you can call Xiao Ai to use it. Supplement: What functions does Xiaoai Speaker have? 1 Xiaoai Speaker has system functions, social functions, entertainment functions, knowledge functions, life functions, smart home, and training plans. Summary/Notes: The Xiao Ai App must be installed on your mobile phone in advance for easy connection and use.

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension
