Detailed configuration and use of Spring Task timing tasks

  • 2020-06-19 10:17:24
  • OfStack

Note Spring's built-in timed task usage.

Timing tasks are used in spring

Use timing tasks based on the xml profile

First configure spring to enable the timing task


<beans xmlns="http://www.springframework.org/schema/beans" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  xmlns:p="http://www.springframework.org/schema/p" 
  xmlns:task="http://www.springframework.org/schema/task" 
  xmlns:context="http://www.springframework.org/schema/context" 
  xmlns:aop="http://www.springframework.org/schema/aop"  
  xsi:schemaLocation="http://www.springframework.org/schema/beans  
  http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 
  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd  
  http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd  
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd  
  http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd  
  http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd"> 

  <task:annotation-driven /> <!--  Timer switch --> 

  <bean id="myTask" class="com.spring.task.MyTask"></bean> 

  <task:scheduled-tasks> 
    <!--  This is the interval 5 Seconds to perform 1 time  --> 
    <task:scheduled ref="myTask" method="show" cron="*/5 * * * * ?" /> 
    <task:scheduled ref="myTask" method="print" cron="*/10 * * * * ?"/> 
  </task:scheduled-tasks> 

  <!--  Automatically scan the package name  -->
  <context:component-scan base-package="com.spring.task" /> 

</beans>

Define your own task execution logic


package com.spring.task; 

/** 
 *  Define the task  
 */ 
public class MyTask { 

  public void show() { 
    System.out.println("show method 1"); 
  } 

  public void print() { 
    System.out.println("print method 1"); 
  } 
}

Use timing tasks based on annotations


package com.spring.task; 
import org.springframework.scheduling.annotation.Scheduled; 
import org.springframework.stereotype.Component; 

/**
 *  Annotation-based timer  
 */
@Component
public class MyTask2 { 

  /**
   *  Timed calculation. In the morning every day  01:00  perform 1 time 
   */
  @Scheduled(cron = "0 0 1 * * *")
  public void show() {
    System.out.println("show method 2"); 
  } 

  /**
   *  Startup time execution 1 Every other time after that 2 Seconds to perform 1 time  
   */
  @Scheduled(fixedRate = 1000*2)  
  public void print() { 
    System.out.println("print method 2");
  }
}

This way, when the project starts, the timer tasks are executed on time according to the rules.

Timing tasks are used in Spring Boot

Spring Boot is more convenient to use.

The introduction of springboot starter package


<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter</artifactId>
</dependency>

Start class addition at program entry @EnableScheduling , turn on the timed task function


@SpringBootApplication
@EnableScheduling
public class Application {

 public static void main(String[] args) {
   SpringApplication.run(Application.class, args);
 }

Define timing task logic


@Component
public class MyTask3 {

 private int count=0;

 @Scheduled(cron="*/6 * * * * ?")
 private void process() {
   System.out.println("this is scheduler task runing "+(count++));
 }
}

Task execution rule description

Let's look at @Scheduled Annotated source code


@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(Schedules.class)
public @interface Scheduled {

  String cron() default "";

  String zone() default "";

  long fixedDelay() default -1;

  String fixedDelayString() default "";

  long fixedRate() default -1;

  String fixedRateString() default "";

  long initialDelay() default -1;

  String initialDelayString() default "";
}

As you can see, there are 8 parameters that can be passed in the annotation:

cron: Specifies the cron expression zone: The server default time zone is used by default. You can set it to java.util.TimeZone The zoneId fixedDelay: The interval, in milliseconds, from the completion of the previous task to the start of the next fixedDelayString: Ibid. The time value is String type fixedRate: The interval, in milliseconds, from the beginning of the previous task to the beginning of the next task fixedRateString: Ibid. The time value is String type initialDelay: Time, in milliseconds, of delay in the first execution of a task initialDelayString: Ibid. The time value is String type

Use of cron expressions

The Cron expression is a string separated by 5 or 6 Spaces and divided into 6 or 7 fields, each field representing a meaning. Cron has the following two syntax formats:

Seconds Minutes Hours DayofMonth Month DayofWeek Year Seconds Minutes Hours DayofMonth Month DayofWeek

The characters that can appear in each field are as follows:

Seconds: Can appear ", - * /"4 characters, valid range of 0-59 integers Minutes: Can appear ", - * /"4 characters, valid range of 0-59 integers Hours: Can appear ", - * /"4 characters, valid range of 0-23 integers DayofMonth: may appear ", - * / ? L W C"8 characters, integer valid from 0 to 31 Month: Can appear ", - * /"4 characters, valid range of 1-12 integers or ES83en-ES84en DayofWeek: can appear ", - * / ? L C #"4 characters, valid in integer range 1-7 or both ES88en-ES89en. 1 means Sunday, 2 means Monday, and so on Year: Can appear ", - * /"4 characters, valid from 1970 to 2099

Each field USES a number, but the following special characters can also appear, meaning:

* : represents any value that matches the field. If * is used in the Minutes field, it means that an event will be triggered every minute. ? : Can only be used in DayofMonth and DayofWeek domains. It also matches any value of the field, but it doesn't. Because DayofMonth and DayofWeek affect each other. For example, if you want to trigger scheduling on the 20th of each month, no matter what day of the week it is, you can only use the following formula: 13, 13, 15, 20 ? Where the last one only works, right? If you use *, it will trigger regardless of the day of the week, which is not the case. - : represents the range, such as using 5-20 in the Minutes domain, which is triggered once per minute from 5 to 20 minutes. @EnableScheduling0 : means that the trigger starts at the starting time, and then triggers once every fixed time. For example, when 5/20 is used in the Minutes field, it means that the trigger is triggered once in 5 minutes, while 25,45 and so on trigger once respectively. , : represents an enumeration value value. For example, using 5,20 in the Minutes domain means it will trigger once per minute at 5 and 20 minutes. L : indicates that finally, only the DayofWeek and DayofMonth domains can appear. If 5L is used in the DayofWeek domain, it means that it is triggered in the last 4 week. W : represents a valid working day (week 1 to Week 5), which can only occur in the DayofMonth domain, and the system will trigger an event on the nearest valid working day to the specified date. For example, using 5W on DayofMonth, if the 5th day is Saturday, it will trigger on the most recent working day: Sunday 5, that is, the 4th. If the 5th is Sunday, it will trigger on the 6th (Monday). If the 5th falls on a day between The 1st and the 5th, it will trigger on the 5th. At another point, the latest search for W will not cross the month. LW : These two characters can be used together to indicate the last working day of a month, i.e. the last 5 week. # : Used to determine the day of the month, which can only appear in the DayofMonth domain. For example, on 4#2, it's the second day of the month.

Related articles: