SpringBoot scheduled task @ enableshcheduling

Posted by beginPHP on Thu, 11 Nov 2021 11:40:37 +0100

1. Import the necessary dependencies in pom.xml:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.1.RELEASE</version>
 </parent>

<dependencies>
    <!-- SpringBoot Core components -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

2. Start scheduled tasks
Set and enable the scheduled task function @ enablesscheduling in the Application.

// An highlighted block
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
 
@SpringBootApplication
@EnableScheduling
public class ResttemplatetestApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(ResttemplatetestApplication.class, args);
    }
}

The @ enableshcheduling annotation is used to find the tasks annotated with @ Scheduled and execute them in the background.
3. Specific implementation class of scheduled task

@RestController  //Other files can be added with @ Component
public class HelloController {
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    @GetMapping("/hello")
    @Scheduled(fixedRate = 2000) //Every 2 seconds
    public Object hello(){
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://story.hhui.top/detail?id=666106231640";
        InnerRes res = restTemplate.getForObject(url, InnerRes.class);
        System.out.println("Scheduled task execution time:" + dateFormat.format(new Date()));
        return  res;
    }
}

4. Run Spring Boot, and the output result is as follows. Print the current time every 2 seconds.

Note: you need to add a comment on the scheduled task class: @ Component
Add @ Scheduled to the specific Scheduled task method to start the Scheduled task.

  • @Scheduled parameter description

  • @Scheduled(fixedRate=3000): execute again 3 seconds after the last execution time point; Execution at a certain rate is calculated from the time when the previous method was executed. If the previous method was blocked, it will not be executed next time. However, the number of times it should be executed during the blocking period will be accumulated. When it is no longer blocked, all these will be executed at once, and then continue to execute at a fixed rate.

  • @Scheduled(fixedDelay=3000): execute again 3 seconds after the last execution; The interval between the execution of the control method is calculated from the end of the previous method execution. If the previous method execution is blocked, the next method execution will be executed until the last execution is completed and the interval is given.

  • @Scheduled(initialDelay=1000, fixedDelay=3000): the execution is delayed for 1 second for the first time, and then executed again at the last execution completion time point of 3 seconds; This timer adds an initialDelay = 10000 to the previous one, which means that after the container is started, the timer will be executed again after a delay of 10 seconds, and then the timer will be executed again every 3 seconds.

  • @Scheduled(cron = "* * *?"): executed according to cron rules;

  • cron expression: for example, if you want to set when to execute every day, you can use it
    cron expressions have special syntax, and feel a little around people, but in short, you can remember some common usage, and special syntax can be checked separately.
    There are 7 digits in cron, but the last digit is year, which can be left blank, so we can write 6 digits:

    • The first digit indicates seconds, and the value is 0-59
    • The second digit indicates score, and the value is 0-59
    • The third digit indicates the hour, and the value is 0-23
    • Fourth digit, date / day, value 1-31
    • The fifth digit is the date month, and the value is 1-12
    • Sixth place, week, value 1-7, Monday, Tuesday... Note: it doesn't mean week 1, week 2
      In addition: 1 means Sunday and 2 means Monday.
    • The seventh is the year, which can be left blank, and the value is 1970-2099

There are also some special symbols in cron, which have the following meanings:

(*)Asterisk: can be understood as the meaning of every, every second, every minute, every day, every month, every year...
(?)Question mark: question mark can only appear in date and week.
(-)Minus sign: represents a range, such as using "10" in the hour field-12",It means from 10 to 12 o'clock, i.e. 10,11,12
(,)Comma: represents a list value, such as "1" in the week field,2,4",Monday, Tuesday, Thursday
(/)Slash: for example: x/y,x Is the starting value, y Is the step size, such as 0 in the first bit (second)/15 That is, starting from 0 seconds, every 15 seconds, and finally 0, 15, 30, 45, 60    In addition:*/y,Equal to 0/y

Here are some examples to verify:

0 0 3 * * ?     At 3:00 every day
0 5 3 * * ?     At 3:05 every day
0 5 3 ? * *     It is executed at 3:05 every day, which is the same as the above
0 5/10 3 * * ?  At 5:00, 15:00, 25:00, 35:00, 45:00 and 55:00 every day
0 10 3 ? * 1    Every Sunday, at 3:10, note: 1 means Sunday    
0 10 3 ? * 1#3  On Sunday, the third week of each month,#No. can only appear in the position of week

cron expression rule: https://www.cnblogs.com/javahr/p/8318728.htmlhttps://www.cnblogs.com/dubhlinn/p/10740838.html

Online Cron Expression Builder: https://cron.qqe2.com/

Topics: Java Spring Spring Boot