Detail the use of the annotation ES1en@Scheduled in Spring3 to create scheduled tasks

  • 2020-06-19 10:10:03
  • OfStack

The use of annotations has been enhanced in Spring3 and the planning task has been enhanced so that creating a planning task is now a two-step process:

Create an Java class, add a method with no arguments and no return value, and decorate the method with the @Scheduled annotation. Add three to the Spring profile < task:**** / > Node;

Finally, the Java class created in step 1 becomes spring managable, either directly in XML or @Component1

The sample is as follows

Planned Tasks:


/** 
 * com.zywang.spring.task.SpringTaskDemo.java 
 * @author ZYWANG 2011-3-9 
 */ 
package com.zywang.spring.task; 
 
import org.springframework.scheduling.annotation.Scheduled; 
import org.springframework.stereotype.Component; 
 
/** 
 * Spring3 @Scheduled  demo  
 * @author ZYWANG 2011-3-9 
 */ 
@Component 
public class SpringTaskDemo { 
 
  @Scheduled(fixedDelay = 5000) 
  void doSomethingWithDelay(){ 
    System.out.println("I'm doing with delay now!"); 
  } 
   
  @Scheduled(fixedRate = 5000) 
  void doSomethingWithRate(){ 
    System.out.println("I'm doing with rate now!"); 
  } 
   
  @Scheduled(cron = "0/5 * * * * *") 
  void doSomethingWith(){ 
    System.out.println("I'm doing with cron now!"); 
  } 
} 

Spring profile:


<?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:task="http://www.springframework.org/schema/task" 
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
    http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"> 
  <!-- Enables the Spring Task @Scheduled programming model --> 
  <task:executor id="executor" pool-size="5" /> 
  <task:scheduler id="scheduler" pool-size="10" /> 
  <task:annotation-driven executor="executor" scheduler="scheduler" /> 
</beans> 

Related articles: