Use the annotation @Scheduled to perform scheduled tasks in Spring

Original: http://dwf07223.blog.51cto.com/8712758/1557145
Reasons why Spring @Scheduled does not workhttp   : //isaacqu.blog.163.com/blog/static/203735102201381993312128/
Several implementations of Spring timing taskshttp ://gong1208.iteye.com/blog/1773177

Annotation @Scheduled can be added to a method as a trigger source, for example, the following method will be called once with a fixed delay of 5 seconds, the cycle is the previous call The completion time of the task is the benchmark. After the previous task is completed, it will be executed again after 5s:
@Scheduled(fixedDelay=5000)
public void doSomething() {    
    // something that should execute periodically
}

   
    If you need to execute at a fixed rate, just change the attribute name specified in the annotation to fixedRate. The following method will be executed at a fixed rate of 5s. This cycle is based on the start time of the previous task and starts from the previous task. Call again 5s after execution:
@Scheduled(fixedRate=5000)
public void doSomething() {
    // something that should execute periodically
}


    For fixed-delay and fixed-rate tasks, you can specify an initial delay that represents the number of milliseconds the method waits before the first call is executed:
@Scheduled(initialDelay=1000, fixedRate=5000)
public void doSomething() {    
    // something that should execute periodically
}


    If simple periodic scheduling is not enough, then cron expressions provide the possibility. For example, the following method will only execute on weekdays:
@Scheduled(cron="*/5 * * * * MON-FRI")
public void doSomething() {    
    // something that should execute on weekdays only
}


    It is also possible to specify the time zone in which the cron expression is invoked by using the zone attribute.



Note:

  1. Spring's annotation @Scheduled needs to be written on the implementation method;

  2. The task method of the timer cannot have a return value (if there is a return value, spring will tell you that there is an error during initialization and a proxytargetclass needs to be set. A certain value is true) and cannot point to any parameters;

  3. If the method needs to interact with other objects in the application context, it is usually implemented through dependency injection;

  4. The implementation class must have component annotation @Component.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326941024&siteId=291194637