How does SpringBoot implement asynchronous and timed tasks?

Written in the front: The Java back-end advanced interview questions necessary for the interview in 2020. A review guide is summarized on Github. The content is detailed, with pictures and texts. Friends who need to learn can star!
GitHub address: https://github.com/abel-max/Java-Study-Note/tree/master

(1) Asynchronous tasks
The demand for asynchronous tasks is often encountered in actual development scenarios. There are many ways to achieve asynchrony in Java, such as multithreading to achieve asynchrony. In SpringBoot, the realization of asynchronous tasks only needs to add two annotations. Add @Async annotation to current class, add @EnableAsync to start class

Write a service, AsynService, let this service pause for 3 seconds before outputting data

@Service
public class AsynService {
    @Async
    public void async(){
        try {
            Thread.sleep(3000);
            System.out.println("执行结束");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Write the controller and call this service class

@RestController
public class IndexController {
    @Autowired
    public AsynService asynService;
    @RequestMapping("/index")
    public String  asynctask(){
        asynService.async();
        return "async task";
    }
}

After running, visit http://localhost:8080/index in the browser, and you will find that because asynchrony is turned on, the browser will output the async task first, and the console will output the end of execution after three seconds.

(2) Timed tasks
I have used timed tasks in the previous spike open source project. In the scene at that time, I polled the database to query expired products every 1 minute. Scheduled tasks have a wide range of applications, such as automatically packing logs at 12 o'clock every day, and backing up at 12 o'clock every night. Realizing timing tasks in SpringBoot only requires two annotations: @Scheduled and @EnableScheduling As before, @Scheduled is used for tasks that need to be executed regularly, and @EnableScheduling is used for startup classes. First, let's write the timed task class:

@Service
public class ScheduleService {

    @Scheduled(cron = "0/10 * * * * ? ")
    public void sayHello(){
        System.out.println("hello");
    }
}

A cron expression needs to be added to the @Scheduled annotation to determine the execution time of the timing task. Here it means that it will be executed every 10 seconds.

Then add the annotation @EnableScheduling to the startup class. Run the project, you will find that a hello will be output every ten seconds.

Guess you like

Origin blog.csdn.net/qwe123147369/article/details/109180522