Summary of Three Ways to Realize Timing Tasks in SpringBoot
- 2021-12-05 06:20:47
- OfStack
SpringBoot3 Ways to Realize Timing Tasks
Three Ways to Realize Timed Tasks
Timer
This is the java. util. Timer class that comes with java. This class allows you to schedule one java. util. TimerTask task. In this way, your program can be executed at a certain frequency, but it cannot run at a specified time. 1 is used less.
ScheduledExecutorService
One class that also comes with jdk; It is a timed task class based on thread pool design, and each scheduled task will be assigned to one thread in the thread pool to execute, that is to say, the tasks are executed concurrently and do not affect each other.
Spring Task
task, which comes with Spring after Spring 3.0, can be regarded as a lightweight Quartz, and it is much simpler to use than Quartz.
Using Timer
This is less used in the project at present, and it is directly pasted with demo code. Specific introduction can be found in api
public class TestTimer {
public static void main(String[] args) {
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
System.out.println("task run:"+ new Date());
}
};
Timer timer = new Timer();
// Schedules the specified task to start repeated fixed delay execution at the specified time. Here is every 3 Second execution 1 Times
timer.schedule(timerTask,10,3000);
}
}
Using ScheduledExecutorService
This method is similar to Timer. Look directly at demo:
public class TestScheduledExecutorService {
public static void main(String[] args) {
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
// Parameters: 1 Task body 2 The delay time of the first execution
// 3 Task execution interval 4 Unit of interval time
service.scheduleAtFixedRate(()->System.out.println("task ScheduledExecutorService "+new Date()), 0, 3, TimeUnit.SECONDS);
}
}
Using Spring Task
1. Simple timed tasks
In the SpringBoot project, we can elegantly use annotations to achieve timing tasks, first creating the project and importing dependencies:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Create a task class:
@Slf4j
@Component
public class ScheduledService {
@Scheduled(cron = "0/5 * * * * *")
public void scheduled(){
log.info("=====>>>>> Use cron {}",System.currentTimeMillis());
}
@Scheduled(fixedRate = 5000)
public void scheduled1() {
log.info("=====>>>>> Use fixedRate{}", System.currentTimeMillis());
}
@Scheduled(fixedDelay = 5000)
public void scheduled2() {
log.info("=====>>>>>fixedDelay{}",System.currentTimeMillis());
}
}
Use the @ EnableScheduling annotation on the main class to turn on support for timed tasks, and then start the project
It can be seen that all three timed tasks have been executed, and they are executed serially in the same thread. If there is only one timed task, it is definitely no problem to do so. When the number of timed tasks increases, if one task is stuck, other tasks cannot be executed.
2. Multithreaded execution
In the traditional Spring project, we can add the configuration of task in the xml configuration file, while in the SpringBoot project, we use the configuration class of config to add the configuration, so we create a new AsyncConfig class
@Configuration
@EnableAsync
public class AsyncConfig {
/*
Here the member variable should use the @Value Read from configuration
*/
private int corePoolSize = 10;
private int maxPoolSize = 200;
private int queueCapacity = 10;
@Bean
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.initialize();
return executor;
}
}
@Configuration
Indicates that the class is a configuration class
@EnableAsync
Enable support for asynchronous events
Then add @ Async to the class or method of the timed task. Finally, restart the project, and each task is in a different thread.
Online cron expression generation: http://qqe2.com/cron/index