當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringBoot2.0 基础案例(04):定时任务和异步任务的使用方式
生活随笔
收集整理的這篇文章主要介紹了
SpringBoot2.0 基础案例(04):定时任务和异步任务的使用方式
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
一、定時(shí)任務(wù)
1、基本概念
按照指定時(shí)間執(zhí)行的程序。
2、使用場(chǎng)景
數(shù)據(jù)分析 數(shù)據(jù)清理 系統(tǒng)服務(wù)監(jiān)控二、同步和異步
1、基本概念
同步調(diào)用
程序按照代碼順序依次執(zhí)行,每一行程序都必須等待上一行程序執(zhí)行完成之后才能執(zhí)行;
異步調(diào)用
順序執(zhí)行時(shí),不等待異步調(diào)用的代碼塊返回結(jié)果就執(zhí)行后面的程序。
2、使用場(chǎng)景
短信通知 郵件發(fā)送 批量數(shù)據(jù)入緩存三、SpringBoot2.0使用定時(shí)器
1、定時(shí)器執(zhí)行規(guī)則注解
@Scheduled(fixedRate = 5000) :上一次開始執(zhí)行時(shí)間點(diǎn)之后5秒再執(zhí)行 @Scheduled(fixedDelay = 5000) :上一次執(zhí)行完畢時(shí)間點(diǎn)之后5秒再執(zhí)行 @Scheduled(initialDelay=1000, fixedRate=5000) :第一次延遲1秒后執(zhí)行,之后按fixedRate的規(guī)則每5秒執(zhí)行一次 @Scheduled(cron="/5") :通過cron表達(dá)式定義規(guī)則2、定義時(shí)間打印定時(shí)器
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; /*** 時(shí)間定時(shí)任務(wù)*/ @Component public class TimeTask {Logger LOG = LoggerFactory.getLogger(TimeTask.class.getName()) ;private static final SimpleDateFormat format =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;/*** 每3秒打印一次系統(tǒng)時(shí)間*/@Scheduled(fixedDelay = 3000)public void systemDate (){LOG.info("當(dāng)前時(shí)間::::"+format.format(new Date()));} }3、啟動(dòng)類開啟定時(shí)器注解
@EnableScheduling // 啟用定時(shí)任務(wù) @SpringBootApplication public class TaskApplication {public static void main(String[] args) {SpringApplication.run(TaskApplication.class,args) ;} }四、SpringBoot2.0使用異步任務(wù)
1、編寫異步任務(wù)類
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; @Component public class AsyncTask {private static final Logger LOGGER = LoggerFactory.getLogger(AsyncTask.class) ;/** [ asyncTask1-2] com.boot.task.config.AsyncTask : ======異步任務(wù)結(jié)束1======* [ asyncTask1-1] com.boot.task.config.AsyncTask : ======異步任務(wù)結(jié)束0======*/// 只配置了一個(gè) asyncExecutor1 不指定也會(huì)默認(rèn)使用@Asyncpublic void asyncTask0 () {try{Thread.sleep(5000);}catch (Exception e){e.printStackTrace();}LOGGER.info("======異步任務(wù)結(jié)束0======");}@Async("asyncExecutor1")public void asyncTask1 () {try{Thread.sleep(5000);}catch (Exception e){e.printStackTrace();}LOGGER.info("======異步任務(wù)結(jié)束1======");} }2、指定異步任務(wù)執(zhí)行的線程池
這里可以不指定,指定執(zhí)行的線城池,可以更加方便的監(jiān)控和管理異步任務(wù)的執(zhí)行。
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; /*** 定義異步任務(wù)執(zhí)行的線程池*/ @Configuration public class TaskPoolConfig {@Bean("asyncExecutor1")public Executor taskExecutor1 () {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();// 核心線程數(shù)10:線程池創(chuàng)建時(shí)候初始化的線程數(shù)executor.setCorePoolSize(10);// 最大線程數(shù)20:線程池最大的線程數(shù),只有在緩沖隊(duì)列滿了之后才會(huì)申請(qǐng)超過核心線程數(shù)的線程executor.setMaxPoolSize(20);// 緩沖隊(duì)列200:用來緩沖執(zhí)行任務(wù)的隊(duì)列executor.setQueueCapacity(200);// 允許線程的空閑時(shí)間60秒:當(dāng)超過了核心線程出之外的線程在空閑時(shí)間到達(dá)之后會(huì)被銷毀executor.setKeepAliveSeconds(60);// 線程池名的前綴:設(shè)置好了之后可以方便定位處理任務(wù)所在的線程池executor.setThreadNamePrefix("asyncTask1-");/*線程池對(duì)拒絕任務(wù)的處理策略:這里采用了CallerRunsPolicy策略,當(dāng)線程池沒有處理能力的時(shí)候,該策略會(huì)直接在 execute 方法的調(diào)用線程中運(yùn)行被拒絕的任務(wù);如果執(zhí)行程序已關(guān)閉,則會(huì)丟棄該任務(wù)*/executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());// 設(shè)置線程池關(guān)閉的時(shí)候等待所有任務(wù)都完成再繼續(xù)銷毀其他的Beanexecutor.setWaitForTasksToCompleteOnShutdown(true);// 設(shè)置線程池中任務(wù)的等待時(shí)間,如果超過這個(gè)時(shí)候還沒有銷毀就強(qiáng)制銷毀,以確保應(yīng)用最后能夠被關(guān)閉,而不是阻塞住。executor.setAwaitTerminationSeconds(600);return executor;} }3、啟動(dòng)類添加異步注解
@EnableAsync // 啟用異步任務(wù) @SpringBootApplication public class TaskApplication {public static void main(String[] args) {SpringApplication.run(TaskApplication.class,args) ;} }4、異步調(diào)用的測(cè)試接口
@RestController public class TaskController {@Resourceprivate AsyncTask asyncTask ;@RequestMapping("/asyncTask")public String asyncTask (){asyncTask.asyncTask0();asyncTask.asyncTask1();return "success" ;} }五、源代碼地址
GitHub:知了一笑 https://github.com/cicadasmile/spring-boot-base
總結(jié)
以上是生活随笔為你收集整理的SpringBoot2.0 基础案例(04):定时任务和异步任务的使用方式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 53、shell常用快捷方式
- 下一篇: SpringCloud微服务:Eurek