How to use scheduled tasks in Spring task
How to use timed tasks in Spring task, for this problem, this article details the corresponding analysis and solution, hoping to help more small partners who want to solve this problem find a simpler and easier way.
use
Now development is based on springboot, and configuring spring task in springboot is especially easy.
The procedure is as follows:
Prepare a springboot project
Add @EnableScheduling annotation to startup class
@SpringBootApplication@EnableSchedulingpublic class DemoApplication {}
Add @Scheduled(fixedDelay = 3 * 1000) annotation to timed methods
@Scheduled(fixedDelay = 3 *1 000)public void p1(){ System.out.println(Thread.currentThread().getName() + " p1");}
Note: The properties of the third annotation are discussed later
@Scheduled Comments
Before we talk about annotation properties, we need to understand the three working modes of Spring timers.
1. fixedDelay
After completing the previous task, wait 3 seconds for the next task.
The schematic diagram is as follows:
The configuration is as follows:
@Scheduled(fixedDelay = 3 * 1000)
2. fixedRate
It predicts when each task should be executed based on the value set.
Assume that the value set is 3 seconds. Then the estimated time for each task is 3 seconds, and the scheduled task starts at 7:00:00.
The schematic diagram is as follows:
The configuration is as follows:
@Scheduled(fixedRate = 3 * 1000)
3. cron
Assume that the setting is executed once every 5 seconds, and it will check every 5 seconds whether the previous task is completed.
The schematic diagram is as follows:
The configuration is as follows:
@Scheduled(cron = "0/3 * * * * ? ") Thinking
problem
After understanding the three working modes of Spring Timer, consider a question, such as the timing function of the following timing diagram.
answer
By default, timed tasks are executed by a single thread. So we need to define a thread pool to execute timed tasks asynchronously.
Specific steps:
Define a thread pool
@Configuration @EnableAsync public class SchedulerAsyncConfig { @Bean public Executor taskExecutor(){ ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setMaxPoolSize(200); executor.setCorePoolSize(10); executor.setQueueCapacity(10); executor.initialize(); return executor; } }
Add @Async annotation to timed tasks.
@Scheduled(fixedDelay = 10) @Async public void p1(){ System.out.println(Thread.currentThread().getName() + " p1"); }
The answer to the question about how to use timed tasks in Spring task is shared here. I hope the above content can be helpful to everyone. If you still have a lot of doubts, you can pay attention to the industry information channel to learn more about it.