Table of Contents
one. Classification
Classified from the perspective of implementation technology, there are currently three main technologies:
In terms of inheritance methods of job classes, they can be divided into two categories:
From the trigger timing of task scheduling, here are mainly the triggers used for jobs, there are mainly the following two types:
two. Usage instructions
Quartz
First, the job class inherits from a specific base class: org.springframework.scheduling.quartz.QuartzJobBean.
Step one: Write task class
Home Java javaTutorial Usage instructions for Spring scheduled tasks

Usage instructions for Spring scheduled tasks

Jun 30, 2017 am 10:37 AM
spring use timing

one. Classification

  • Classified from the perspective of implementation technology, there are currently three main technologies:

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

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

  3. 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:

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

  2. 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:
  1. Triggers once every specified time. The corresponding trigger in Quartz is: org.springframework.scheduling.quartz.SimpleTriggerBean

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

Java code Usage instructions for Spring scheduled tasks
  1. import org.quartz.JobExecutionContext;

  2. ##import org.quartz.JobExecutionException;

  3. import org.springframework.scheduling.quartz.QuartzJobBean;

  4. ##public

    class Job1 extends QuartzJobBean {

  5. private
  6. int timeout;

  7. private
  8. static

    int i = 0;

  9. //After the scheduling factory is instantiated, the scheduling starts after the timeout time
  10. ##public
  11. void setTimeout(
  12. int timeout) {

    ##this.timeout = timeout;

  13. }

  14. ##/**

  15. * Specific tasks to be scheduled

  16. */

  17. ##@Override

  18. protected void executeInternal(JobExecutionContext context)

  19. throws JobExecutionException {

  20. System.out.println(

    "The scheduled task is being executed...");

  21. }

    }
  22. Step 2: Configure the job class JobDetailBean# in the spring configuration file

##Xml code

  1. bean name="job1" class="org.springframework.scheduling.quartz.JobDetailBean">

  2. #property name= "jobClass" value="com.gy.Job1" />

  3. ##property name="jobDataAsMap">

#map

>

## entry
  • key=

    "timeout" value="0" /> ##

    map
  • >
  • property
  • >
  • ##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.

  • Step 3: Configure the triggering method (trigger) of job scheduling

    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

    Usage instructions for Spring scheduled tasksbean
    id=
      "simpleTrigger"
    1. class=

      "org.springframework.scheduling.quartz.SimpleTriggerBean"> ##property name=

      "jobDetail"
    2. ref=
    3. "job1"

      /> #property name="startDelay"

      value=
    4. "0"
    5. />

      property name="repeatInterval" value=

      "2000"
    6. />
    7. bean>

    8. The second CronTriggerBean supports running once at a specified time, such as once every day at 12:00. The configuration method is as follows:

      Xml code
    1. bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">

    2. #property name= "jobDetail" ref="job1" />

    3. ##>

    4. property name="cronExpression" value="0 0 12 * * ?" />
    5. ##
    6. bean

      >

      ## See the appendix for the syntax of cronExpression expression.
    Step 4: Configure the scheduling factory

    Xml code

    Usage instructions for Spring scheduled tasks
    bean
  • class=

    "org.springframework.scheduling.quartz.SchedulerFactoryBean"> #property

  • name=
  • "triggers"

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

  • Second, the job class does not inherit a specific base class.

    Spring can support this method thanks to two classes:

    org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean

    org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean

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

    public

    class Job2 {
    Usage instructions for Spring scheduled tasks
    ##public
      void doJob2() {
    1. System.out.println(

      "Does not inherit QuartzJobBean mode - scheduling is in progress...");
    2. }

    3. }
    4. It can be seen that this is an ordinary class and has one method.
    5. Step 2: Configure job class

    6. Xml code
    1. bean id="job2"

    2. ##class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">

    3. property name="targetObject">

    4. ##bean class="com.gy.Job2" />
    5. property>

    6. ##property

      name="targetMethod" value="doJob2" />

      property

      name="concurrent" value="false" />

      #bean
    7. >

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

    Step 3: Configure the triggering method (trigger) of job scheduling

    There are two types of job triggers in Quartz, namely

    org .springframework.scheduling.quartz.SimpleTriggerBean

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

    Usage instructions for Spring scheduled tasks## bean
    id=
      "simpleTrigger"
    1. class=

      "org.springframework.scheduling.quartz.SimpleTriggerBean"> ##property name=

      "jobDetail"
    2. ref=
    3. "job2"

      /> #property name="startDelay"

      value=
    4. "0"
    5. />

      property name= "repeatInterval" value=

      "2000"
    6. />
    7. #bean>

    8. The second CronTriggerBean supports running once at a specified time, such as once every day at 12:00. The configuration method is as follows:

      Xml code
    1. bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">

    2. #property name= "jobDetail" ref="job2" />

    3. ##>

    4. property name="cronExpression" value="0 0 12 * * ?" />
    5. ##
    6. bean

      >

      ##You can choose any one of the above two scheduling methods according to the actual situation.
    Step 4: Configure the scheduling factory

    Xml code

    Usage instructions for Spring scheduled tasks
    bean
  • class=

    "org.springframework.scheduling.quartz.SchedulerFactoryBean"> #property

  • name=
  • "triggers"

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

  • At this point, the basic configuration of Quartz in spring has been introduced. Of course, before using it, you need to import the corresponding spring package and Quartz package. There is no need for more. said.
    In fact, it can be seen that the configuration of Quartz seems quite complicated. There is no way, because Quartz is actually a heavyweight tool. If we just want to simply execute a few simple scheduled tasks, is there anything simpler? Tools, yes!

    Please see my introduction to Spring task below.

    Spring-Task

    The 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

    1. import org.springframework.stereotype.Service;

    2. @Service

    3. public class TaskJob {

    4. #public void job1() {

    5. System.out.println("Task in progress...");

    6. }

    7. }

    Step 2: Add the namespace and Description

    Xml code
    Usage instructions for Spring scheduled tasks
    1. ##beans xmlns= "http://www.springframework.org/schema/beans"
    2. ##xmlns:task=
    3. "http://www.springframework.org/schema/task"

      . . . . . .
    4. ##​

      xsi:schemaLocation=
    5. "http://www.springframework.org/schema/task "
    6. >

    7. Step 3: Set specific tasks in the spring configuration file

    Xml code

    Usage instructions for Spring scheduled tasks
    ##task:scheduled-tasks
      >
    1.      task:scheduled

    2. ref=
    3. "taskJob"

      method="job1" cron="0 * * * * ?"/> #task:scheduled-tasks

      >
    4. ##context:component-scan

      base-package=

      " com.gy.mytask " />
    5. ## Description: The ref parameter specifies the task class, the method specifies the method that needs to be run, cron and cronExpression expressions, the specific writing method is not introduced here, details See the appendix to the previous article. Needless to say, this configuration is used for spring scanning annotations.

      The configuration is complete here, isn’t it very simple?
    Second: Use annotation form

    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

    1. @Target({java.lang.annotation.ElementType.METHOD, java.lang.annotation.ElementType.ANNOTATION_TYPE})

    2. @Retention(RetentionPolicy.RUNTIME)

    3. ##@Documented

    4. public @interface Scheduled

    5. {

    6. public abstract String cron() ;

    7. ##public

      abstract long fixedDelay();

    8. ##public
    9. abstract

      long fixedRate();

      }
    10. It can be seen that this annotation has three methods or parameters, which respectively mean: :
    cron: Specify cron expression

    fixedDelay: Official document explanation: An interval-based trigger where the interval is measured from the completion time of the previous task. The time unit value is measured in milliseconds. It means the interval from the completion of the previous task to the start of the next task, the unit is milliseconds.

    fixedRate: Official document explanation: An interval-based trigger where the interval is measured from the start time of the previous task. The time unit value is measured in milliseconds. That is, from the start of the previous task to the next task The starting interval in milliseconds.

    Let me configure it.

    Step one: Write pojo

    Java code
    Usage instructions for Spring scheduled tasks
      import org.springframework.scheduling.annotation.Scheduled;
    1. ##import org.springframework.stereotype.Component;
    2. ##@Component(“taskJob”)

    3. ##public class TaskJob {

    4. ##@Scheduled(cron = "0 0 3 * * ?")

    5. # PUBLIC VOID JOB1 () {

    6. ## System.out.println ("Mission is in progress. . ”); # }

    7. ##}
    8. # Step 2: Add task-related configuration:

    9. Xml code

    1. xml version="1.0" encoding="UTF-8"?>  

    2. beans xmlns="http://www.springframework.org/schema/beans"  

    3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"  

    4.     xmlns:context="http://www.springframework.org/schema/context"  

    5.     xmlns:tx="http://www.springframework.org/schema/tx"  

    6.     xmlns:task="http://www.springframework.org/schema/task"  

    7.     xsi:schemaLocation="  

    8.          "  

    9.     default-lazy-init="false">  

    10.     context:annotation-config />  

    11.     >  

    12.     context:component-scan base-package="com.gy.mytask" />  

    13. >  

    14.     task:annotation-driven scheduler="qbScheduler" mode="proxy"/>  

    15.     task:scheduler id="qbScheduler" pool-size="10"/>  

    Note: In theory, you only need to add the configuration sentence . These parameters are not necessary.

    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!

    Statement of this Website
    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

    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)
    2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Repo: How To Revive Teammates
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Hello Kitty Island Adventure: How To Get Giant Seeds
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    How to use mdf and mds files How to use mdf and mds files Feb 19, 2024 pm 05:36 PM

    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.

    What software is crystaldiskmark? -How to use crystaldiskmark? What software is crystaldiskmark? -How to use crystaldiskmark? Mar 18, 2024 pm 02:58 PM

    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

    How to download foobar2000? -How to use foobar2000 How to download foobar2000? -How to use foobar2000 Mar 18, 2024 am 10:58 AM

    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

    Use Spring Boot and Spring AI to build generative artificial intelligence applications Use Spring Boot and Spring AI to build generative artificial intelligence applications Apr 28, 2024 am 11:46 AM

    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

    How to use Baidu Netdisk app How to use Baidu Netdisk app Mar 27, 2024 pm 06:46 PM

    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.

    How to use NetEase Mailbox Master How to use NetEase Mailbox Master Mar 27, 2024 pm 05:32 PM

    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

    How to use Xiaoai Speaker How to connect Xiaoai Speaker to mobile phone How to use Xiaoai Speaker How to connect Xiaoai Speaker to mobile phone Feb 22, 2024 pm 05:19 PM

    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.

    BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

    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

    See all articles