Spring 5 source code analysis of asynchronous and scheduled tasks in spring

Java provides many ways to create thread pools and gets a future instance as the result of the task. Spring is also a piece of cake. Through its scheduling package, the task thread can be executed in the background.

In the first part of this article, we will discuss some of the basics of performing planned tasks in spring. After that, we will explain how these classes work together to start and execute planned tasks. The next section describes the configuration of scheduled and asynchronous tasks. Finally, let's write a demo to see how to plan tasks through unit tests.

What are asynchronous tasks in spring?

Before we formally enter the topic, we need to understand two different concepts implemented by spring: asynchronous task and scheduling task. Obviously, the two have one thing in common: both work in the background. However, there are great differences between them. Scheduling tasks is different from asynchronous tasks, and its role is exactly the same as cron jobs in Linux (there are also scheduled tasks in Windows). For example, if a task must be executed every 40 minutes, this can be configured through XML files or annotations. Simple asynchronous tasks can be executed in the background without configuring the execution frequency.

Because they are two different task types, their executors are naturally different. The first one looks a bit like the concurrency executor of Java. Here, I will write an article about the executor in Java to learn more about it. According to the spring document taskexecutor, it provides spring based abstraction to handle thread pools, which can also be understood through its class annotations. Another abstract interface is taskscheduler, which is used to schedule tasks at a given point in time in the future and execute them once or periodically.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>