Home >Java >javaTutorial >Usage instructions for Spring scheduled tasks

Usage instructions for Spring scheduled tasks

零下一度
零下一度Original
2017-06-30 10:37:121391browse

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