詳解SpringBoot Schedule配置
1. 定時任務實現方式
定時任務實現方式:
- Java自帶的java.util.Timer類,這個類允許你調度一個java.util.TimerTask任務。使用這種方式可以讓你的程序按照某一個頻度執(zhí)行,但不能在指定時間運行。一般用的較少,這篇文章將不做詳細介紹。
- 使用Quartz,這是一個功能比較強大的的調度器,可以讓你的程序在指定時間執(zhí)行,也可以按照某一個頻度執(zhí)行,配置起來稍顯復雜,有空介紹。
- SpringBoot自帶的Scheduled,可以將它看成一個輕量級的Quartz,而且使用起來比Quartz簡單許多,本文主要介紹。
定時任務執(zhí)行方式:
- 單線程(串行)
- 多線程(并行)
2. 創(chuàng)建定時任務
package com.autonavi.task.test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import com.autonavi.task.ScheduledTasks; @Component public class ScheduledTest { private static final Logger logger = LoggerFactory.getLogger(ScheduledTasks.class); @Scheduled(cron="0 0/2 * * * ?") public void executeFileDownLoadTask() { // 間隔2分鐘,執(zhí)行任務 Thread current = Thread.currentThread(); System.out.println("定時任務1:"+current.getId()); logger.info("ScheduledTest.executeFileDownLoadTask 定時任務1:"+current.getId()+ ",name:"+current.getName()); } }
@Scheduled 注解用于標注這個方法是一個定時任務的方法,有多種配置可選。cron支持cron表達式,指定任務在特定時間執(zhí)行;fixedRate以特定頻率執(zhí)行任務;fixedRateString以string的形式配置執(zhí)行頻率。
3. 啟動定時任務
@SpringBootApplication @EnableScheduling public class App { private static final Logger logger = LoggerFactory.getLogger(App.class); public static void main(String[] args) { SpringApplication.run(App.class, args); logger.info("start"); } }
其中 @EnableScheduling 注解的作用是發(fā)現注解@Scheduled的任務并后臺執(zhí)行。
Springboot本身默認的執(zhí)行方式是串行執(zhí)行,也就是說無論有多少task,都是一個線程串行執(zhí)行,并行需手動配置
4. 并行任務
繼承SchedulingConfigurer類并重寫其方法即可,如下:
@Configuration @EnableScheduling public class ScheduleConfig implements SchedulingConfigurer { @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.setScheduler(taskExecutor()); } @Bean(destroyMethod="shutdown") public Executor taskExecutor() { return Executors.newScheduledThreadPool(100); } }
再次執(zhí)行之前的那個Demo,會欣然發(fā)現已經是并行執(zhí)行了!
5. 異步并行任務
import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.annotation.AsyncConfigurer; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.SchedulingConfigurer; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.scheduling.config.ScheduledTaskRegistrar; @Configuration @EnableScheduling @EnableAsync( mode = AdviceMode.PROXY, proxyTargetClass = false, order = Ordered.HIGHEST_PRECEDENCE ) @ComponentScan( basePackages = "hello" ) public class RootContextConfiguration implements AsyncConfigurer, SchedulingConfigurer { @Bean public ThreadPoolTaskScheduler taskScheduler() { ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); scheduler.setPoolSize(20); scheduler.setThreadNamePrefix("task-"); scheduler.setAwaitTerminationSeconds(60); scheduler.setWaitForTasksToCompleteOnShutdown(true); return scheduler; } @Override public Executor getAsyncExecutor() { Executor executor = this.taskScheduler(); return executor; } @Override public void configureTasks(ScheduledTaskRegistrar registrar) { TaskScheduler scheduler = this.taskScheduler(); registrar.setTaskScheduler(scheduler); } }
在啟動的main方法加入額外配置:
@SpringBootApplication public class Application { public static void main(String[] args) throws Exception { AnnotationConfigApplicationContext rootContext = new AnnotationConfigApplicationContext(); rootContext.register(RootContextConfiguration.class); rootContext.refresh(); } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
- Spring boot如何通過@Scheduled實現定時任務及多線程配置
- springboot 定時任務@Scheduled實現解析
- springboot schedule 解決定時任務不執(zhí)行的問題
- SpringBoot2 task scheduler 定時任務調度器四種方式
- springboot集成schedule實現定時任務
- Spring Boot利用@Async異步調用:ThreadPoolTaskScheduler線程池的優(yōu)雅關閉詳解
- spring-boot通過@Scheduled配置定時任務及定時任務@Scheduled注解的方法
- SpringBoot定時任務兩種(Spring Schedule 與 Quartz 整合 )實現方法
- SpringBoot配置及使用Schedule過程解析
相關文章
關于SpringBoot大文件RestTemplate下載解決方案
這篇文章主要介紹了SpringBoot大文件RestTemplate下載解決方案,最近結合網上案例及自己總結,寫了一個分片下載tuling/fileServer項目,需要的朋友可以參考下2021-10-10java后端+前端使用WebSocket實現消息推送的詳細流程
后端向前端推送消息就需要長連接,首先想到的就是websocket,下面這篇文章主要給大家介紹了關于java后端+前端使用WebSocket實現消息推送的詳細流程,需要的朋友可以參考下2022-10-10Spring-cloud Config Server的3種配置方式
這篇文章主要介紹了Spring-cloud Config Server的3種配置方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09如何基于SpringSecurity的@PreAuthorize實現自定義權限校驗方法
spring Security提供有若干個過濾器,它們能夠攔截Servlet請求,并將這些請求轉給認證和訪問決策管理器處理,從而增強安全性,下面這篇文章主要給大家介紹了關于如何基于SpringSecurity的@PreAuthorize實現自定義權限校驗方法的相關資料,需要的朋友可以參考下2023-03-03