In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article is about how SpringBoot2 uses timed tasks and asynchronous tasks. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
I. timed tasks 1. Basic concepts
A program that is executed at a specified time.
2. Use scenario data to analyze data cleaning system service monitoring 2, synchronous and asynchronous 1, basic concepts
Synchronous call
Programs are executed in code order, and each line of programs must wait for the execution of the previous line before it can be executed.
Asynchronous invocation
When executed sequentially, the following program is executed without waiting for the block of code to be called asynchronously to return the result.
2. Use scenario SMS to notify email to send batch data to cache 3. SpringBoot2 uses timer 1, timer execution rule note @ Scheduled (fixedRate=5000): execute @ Scheduled (fixedDelay = 5000) 5 seconds after the last execution time point: execute @ Scheduled (initialDelay=1000, fixedRate=5000) 5 seconds after the last execution time point: execute after 1 second delay for the first time Then execute @ Scheduled (cron= "/ 5") every 5 seconds according to fixedRate's rule: define rule 2 through cron expression, define time to print timer import org.slf4j.Logger Import org.slf4j.LoggerFactory;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;import java.text.SimpleDateFormat;import java.util.Date;/** * timed tasks * / @ Componentpublic class TimeTask {Logger LOG = LoggerFactory.getLogger (TimeTask.class.getName ()); private static final SimpleDateFormat format = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss") / * system time is printed every 3 seconds * / @ Scheduled (fixedDelay = 3000) public void systemDate () {LOG.info ("current time:" + format.format (new Date () }} 3. Startup class starts timer note @ EnableScheduling / / enables timed task @ SpringBootApplicationpublic class TaskApplication {public static void main (String [] args) {SpringApplication.run (TaskApplication.class,args);} 4. SpringBoot2.0 uses asynchronous task 1 and writes asynchronous task class import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.scheduling.annotation.Async;import org.springframework.stereotype.Component @ Componentpublic class AsyncTask {private static final Logger LOGGER = LoggerFactory.getLogger (AsyncTask.class) / * * [asyncTask1-2] com.boot.task.config.AsyncTask: = Asynchronous Task end 1 = * [asyncTask1-1] com.boot.task.config.AsyncTask: = Asynchronous Task end 0 = * / / only one asyncExecutor1 is configured and @ Async public void asyncTask0 () {try {Thread.sleep (5000) is used by default } catch (Exception e) {e.printStackTrace ();} LOGGER.info ("= asynchronous task end 0 =");} @ Async ("asyncExecutor1") public void asyncTask1 () {try {Thread.sleep (5000);} catch (Exception e) {e.printStackTrace () } LOGGER.info ("= asynchronous task end 1 =");}} 2. Specify the thread pool for asynchronous task execution
It is not necessary to specify the line city for execution, which makes it easier to monitor and manage the execution of asynchronous tasks.
Import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;import java.util.concurrent.Executor;import java.util.concurrent.ThreadPoolExecutor;/** * defines the thread pool for asynchronous task execution * / @ Configurationpublic class TaskPoolConfig {@ Bean ("asyncExecutor1") public Executor taskExecutor1 () {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor () / / number of core threads 10: number of threads initialized when the thread pool is created executor.setCorePoolSize (10); / / maximum number of threads 20: the maximum number of threads in the thread pool. Only when the buffer queue is full will the thread executor.setMaxPoolSize (20) be applied for exceeding the number of core threads. / / buffer queue 200: the queue used to buffer the execution of tasks executor.setQueueCapacity (200); / / allow the idle time of threads to be 60 seconds: when threads other than the core thread arrive in idle time, the executor.setKeepAliveSeconds will be destroyed (60) / / prefix of the thread pool name: once set, you can easily locate the thread pool executor.setThreadNamePrefix ("asyncTask1-") in which the task is processed; / * the thread pool's strategy for handling rejected tasks: the CallerRunsPolicy policy is adopted here. When the thread pool has no processing capacity, this policy will directly run the rejected task in the calling thread of the execute method. If the executor is closed, the task * / executor.setRejectedExecutionHandler (new ThreadPoolExecutor.CallerRunsPolicy ()) will be discarded; / / when the thread pool is closed, wait for all tasks to complete before continuing to destroy other Bean executor.setWaitForTasksToCompleteOnShutdown (true). / / set the waiting time for the task in the thread pool, and force it to be destroyed if it is not destroyed beyond this time, to ensure that the application can finally be closed instead of blocked. Executor.setAwaitTerminationSeconds; return executor;}} 3. Add asynchronous annotations to startup class @ EnableAsync / / enable asynchronous tasks @ SpringBootApplicationpublic class TaskApplication {public static void main (String [] args) {SpringApplication.run (TaskApplication.class,args);}} 4. Test interface for asynchronous calls @ RestControllerpublic class TaskController {@ Resource private AsyncTask asyncTask @ RequestMapping ("/ asyncTask") public String asyncTask () {asyncTask.asyncTask0 (); asyncTask.asyncTask1 (); return "success";}} Thank you for reading! This is the end of this article on "how to use timed tasks and asynchronous tasks in SpringBoot2". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.