最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

帶你3分鐘帶你搞定Spring Boot中Schedule

 更新時間:2024年07月19日 15:02:51   作者:潘志的研發(fā)筆記  
本文主要圍繞Spring scheduled應(yīng)用實踐進(jìn)行分享,如果是單體應(yīng)用,使用SpringBoot內(nèi)置的@scheduled注解可以解決大部分業(yè)務(wù)需求,對Spring Boot中Schedule 相關(guān)知識感興趣的朋友一起看看吧

一、背景介紹

在實際的業(yè)務(wù)開發(fā)過程中,我們經(jīng)常會需要定時任務(wù)來幫助我們完成一些工作,例如每天早上 6 點生成銷售報表、每晚 23 點清理臟數(shù)據(jù)等等。

如果你當(dāng)前使用的是 SpringBoot 來開發(fā)項目,那么完成這些任務(wù)會非常容易!

SpringBoot 默認(rèn)已經(jīng)幫我們完成了相關(guān)定時任務(wù)組件的配置,我們只需要添加相應(yīng)的注解@Scheduled就可以實現(xiàn)任務(wù)調(diào)度!

二、方案實踐

2.1、pom 包配置

pom包里面只需要引入Spring Boot Starter包即可!

???????
<dependencies>
    <!--spring boot核心-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <!--spring boot 測試-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

???????2.2、啟動類啟用定時調(diào)度

在啟動類上面加上@EnableScheduling即可開啟定時

@SpringBootApplication
@EnableScheduling
public class ScheduleApplication {
    public static void main(String[] args) {
        SpringApplication.run(ScheduleApplication.class, args);
    }
}

???????2.3、創(chuàng)建定時任務(wù)

Spring Scheduler支持四種形式的任務(wù)調(diào)度!

  • fixedRate:固定速率執(zhí)行,例如每5秒執(zhí)行一次
  • fixedDelay:固定延遲執(zhí)行,例如距離上一次調(diào)用成功后2秒執(zhí)行
  • initialDelay:初始延遲任務(wù),例如任務(wù)開啟過5秒后再執(zhí)行,之后以固定頻率或者間隔執(zhí)行
  • cron:使用 Cron 表達(dá)式執(zhí)行定時任務(wù)

2.3.1、固定速率執(zhí)行

你可以通過使用fixedRate參數(shù)以固定時間間隔來執(zhí)行任務(wù),示例如下:

@Component
public class SchedulerTask {
    private static final Logger log = LoggerFactory.getLogger(SchedulerTask.class);
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /**
     * fixedRate:固定速率執(zhí)行。每5秒執(zhí)行一次。
     */
    @Scheduled(fixedRate = 5000)
    public void runWithFixedRate() {
        log.info("Fixed Rate Task,Current Thread : {},The time is now : {}", Thread.currentThread().getName(), dateFormat.format(new Date()));
    }
}

運行ScheduleApplication主程序,即可看到控制臺輸出效果:

Fixed Rate Task,Current Thread : scheduled-thread-1,The time is now : 2020-12-15 11:46:00
Fixed Rate Task,Current Thread : scheduled-thread-1,The time is now : 2020-12-15 11:46:10
...

???????2.3.2、固定延遲執(zhí)行

你可以通過使用fixedDelay參數(shù)來設(shè)置上一次任務(wù)調(diào)用完成與下一次任務(wù)調(diào)用開始之間的延遲時間,示例如下:

@Component
public class SchedulerTask {
    private static final Logger log = LoggerFactory.getLogger(SchedulerTask.class);
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /**
     * fixedDelay:固定延遲執(zhí)行。距離上一次調(diào)用成功后2秒后再執(zhí)行。
     */
    @Scheduled(fixedDelay = 2000)
    public void runWithFixedDelay() {
        log.info("Fixed Delay Task,Current Thread : {},The time is now : {}", Thread.currentThread().getName(), dateFormat.format(new Date()));
    }
}

控制臺輸出效果:

Fixed Delay Task,Current Thread : scheduled-thread-1,The time is now : 2020-12-15 11:46:00
Fixed Delay Task,Current Thread : scheduled-thread-1,The time is now : 2020-12-15 11:46:02
...

???????2.3.3、初始延遲任務(wù)

你可以通過使用initialDelay參數(shù)與fixedRate或者fixedDelay搭配使用來實現(xiàn)初始延遲任務(wù)調(diào)度。

@Component
public class SchedulerTask {
    private static final Logger log = LoggerFactory.getLogger(SchedulerTask.class);
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /**
     * initialDelay:初始延遲。任務(wù)的第一次執(zhí)行將延遲5秒,然后將以5秒的固定間隔執(zhí)行。
     */
    @Scheduled(initialDelay = 5000, fixedRate = 5000)
    public void reportCurrentTimeWithInitialDelay() {
        log.info("Fixed Rate Task with Initial Delay,Current Thread : {},The time is now : {}", Thread.currentThread().getName(), dateFormat.format(new Date()));
    }
}

控制臺輸出效果:

Fixed Rate Task with Initial Delay,Current Thread : scheduled-thread-1,The time is now : 2020-12-15 11:46:05
Fixed Rate Task with Initial Delay,Current Thread : scheduled-thread-1,The time is now : 2020-12-15 11:46:10
...

???????2.3.4、使用 Cron 表達(dá)式

Spring Scheduler同樣支持Cron表達(dá)式,如果以上簡單參數(shù)都不能滿足現(xiàn)有的需求,可以使用 cron 表達(dá)式來定時執(zhí)行任務(wù)。

關(guān)于cron表達(dá)式的具體用法,可以點擊參考這里: https://cron.qqe2.com/

@Component
public class SchedulerTask {
    private static final Logger log = LoggerFactory.getLogger(SchedulerTask.class);
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /**
     * cron:使用Cron表達(dá)式。每6秒中執(zhí)行一次
     */
    @Scheduled(cron = "*/6 * * * * ?")
    public void reportCurrentTimeWithCronExpression() {
        log.info("Cron Expression,Current Thread : {},The time is now : {}", Thread.currentThread().getName(), dateFormat.format(new Date()));
    }
}

控制臺輸出效果:

Cron Expression,Current Thread : scheduled-thread-1,The time is now : 2020-12-15 11:46:06
Cron Expression,Current Thread : scheduled-thread-1,The time is now : 2020-12-15 11:46:12
...

???????2.4、異步執(zhí)行定時任務(wù)

在介紹異步執(zhí)行定時任務(wù)之前,我們先看一個例子!

在下面的示例中,我們創(chuàng)建了一個每隔2秒執(zhí)行一次的定時任務(wù),在任務(wù)里面大概需要花費 3 秒鐘,猜猜執(zhí)行結(jié)果如何?

@Component
public class AsyncScheduledTask {
    private static final Logger log = LoggerFactory.getLogger(AsyncScheduledTask.class);
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Scheduled(fixedRate = 2000)
    public void runWithFixedDelay() {
        try {
            TimeUnit.SECONDS.sleep(3);
            log.info("Fixed Delay Task, Current Thread : {} : The time is now {}", Thread.currentThread().getName(), dateFormat.format(new Date()));
        } catch (InterruptedException e) {
            log.error("錯誤信息",e);
        }
    }
}

控制臺輸入結(jié)果:

Fixed Delay Task, Current Thread : scheduling-1 : The time is now 2020-12-15 17:55:26
Fixed Delay Task, Current Thread : scheduling-1 : The time is now 2020-12-15 17:55:31
Fixed Delay Task, Current Thread : scheduling-1 : The time is now 2020-12-15 17:55:36
Fixed Delay Task, Current Thread : scheduling-1 : The time is now 2020-12-15 17:55:41
...

很清晰的看到,任務(wù)調(diào)度頻率變成了每隔5秒調(diào)度一次!

這是為啥呢?

Current Thread : scheduling-1輸出結(jié)果可以很看到,任務(wù)執(zhí)行都是同一個線程!默認(rèn)的情況下,@Scheduled任務(wù)都在 Spring 創(chuàng)建的大小為 1 的默認(rèn)線程池中執(zhí)行!

更直觀的結(jié)果是,任務(wù)都是串行執(zhí)行!

下面,我們將其改成異步線程來執(zhí)行,看看效果如何?

@Component
@EnableAsync
public class AsyncScheduledTask {
    private static final Logger log = LoggerFactory.getLogger(AsyncScheduledTask.class);
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Async
    @Scheduled(fixedDelay = 2000)
    public void runWithFixedDelay() {
        try {
            TimeUnit.SECONDS.sleep(3);
            log.info("Fixed Delay Task, Current Thread : {} : The time is now {}", Thread.currentThread().getName(), dateFormat.format(new Date()));
        } catch (InterruptedException e) {
            log.error("錯誤信息",e);
        }
    }
}

控制臺輸出結(jié)果:

Fixed Delay Task, Current Thread : SimpleAsyncTaskExecutor-1 : The time is now 2020-12-15 18:55:26
Fixed Delay Task, Current Thread : SimpleAsyncTaskExecutor-2 : The time is now 2020-12-15 18:55:28
Fixed Delay Task, Current Thread : SimpleAsyncTaskExecutor-3 : The time is now 2020-12-15 18:55:30
...

任務(wù)的執(zhí)行頻率不受方法內(nèi)的時間影響,以并行方式執(zhí)行!

2.5、自定義任務(wù)線程池

雖然默認(rèn)的情況下,@Scheduled任務(wù)都在 Spring 創(chuàng)建的大小為 1 的默認(rèn)線程池中執(zhí)行,但是我們也可以自定義線程池,只需要實現(xiàn)SchedulingConfigurer類即可!

自定義線程池示例如下:

@Configuration
public class SchedulerConfig implements SchedulingConfigurer {
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
        //線程池大小為10
        threadPoolTaskScheduler.setPoolSize(10);
        //設(shè)置線程名稱前綴
        threadPoolTaskScheduler.setThreadNamePrefix("scheduled-thread-");
        //設(shè)置線程池關(guān)閉的時候等待所有任務(wù)都完成再繼續(xù)銷毀其他的Bean
        threadPoolTaskScheduler.setWaitForTasksToCompleteOnShutdown(true);
        //設(shè)置線程池中任務(wù)的等待時間,如果超過這個時候還沒有銷毀就強制銷毀,以確保應(yīng)用最后能夠被關(guān)閉,而不是阻塞住
        threadPoolTaskScheduler.setAwaitTerminationSeconds(60);
        //這里采用了CallerRunsPolicy策略,當(dāng)線程池沒有處理能力的時候,該策略會直接在 execute 方法的調(diào)用線程中運行被拒絕的任務(wù);如果執(zhí)行程序已關(guān)閉,則會丟棄該任務(wù)
        threadPoolTaskScheduler.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        threadPoolTaskScheduler.initialize();
        scheduledTaskRegistrar.setTaskScheduler(threadPoolTaskScheduler);
    }
}

我們啟動服務(wù),看看cron任務(wù)示例調(diào)度效果:

Cron Expression,Current Thread : scheduled-thread-1,The time is now : 2020-12-15 20:46:00
Cron Expression,Current Thread : scheduled-thread-2,The time is now : 2020-12-15 20:46:06
Cron Expression,Current Thread : scheduled-thread-3,The time is now : 2020-12-15 20:46:12
Cron Expression,Current Thread : scheduled-thread-4,The time is now : 2020-12-15 20:46:18
....

當(dāng)前線程名稱已經(jīng)被改成自定義scheduled-thread的前綴!

三、小結(jié)

本文主要圍繞Spring scheduled應(yīng)用實踐進(jìn)行分享,如果是單體應(yīng)用,使用SpringBoot內(nèi)置的@scheduled注解可以解決大部分業(yè)務(wù)需求,上手非常容易!

項目源代碼地址:spring-boot-example-scheduled

四、參考

1、https://springboot.io/t/topic/2758

到此這篇關(guān)于3分鐘帶你搞定Spring Boot中Schedule 的文章就介紹到這了,更多相關(guān)Spring Boot中Schedule 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • java UDP實現(xiàn)一個聊天工具的示例代碼

    java UDP實現(xiàn)一個聊天工具的示例代碼

    這篇文章主要介紹了java UDP實現(xiàn)一個聊天工具的示例代碼,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-01-01
  • Windows下安裝ElasticSearch的方法(圖文)

    Windows下安裝ElasticSearch的方法(圖文)

    這篇文章主要介紹了Windows下安裝ElasticSearch的方法(圖文),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-01-01
  • Spring Boot Web 靜態(tài)文件緩存處理的方法

    Spring Boot Web 靜態(tài)文件緩存處理的方法

    本篇文章主要介紹了Spring Boot Web 靜態(tài)文件緩存處理的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-02-02
  • java+socket實現(xiàn)簡易局域網(wǎng)聊天室

    java+socket實現(xiàn)簡易局域網(wǎng)聊天室

    這篇文章主要為大家詳細(xì)介紹了java+socket實現(xiàn)簡易局域網(wǎng)聊天室,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-05-05
  • springboot application.properties 文件注入數(shù)組方式

    springboot application.properties 文件注入數(shù)組方式

    這篇文章主要介紹了springboot application.properties 文件注入數(shù)組方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • Java鎖之可重入鎖介紹

    Java鎖之可重入鎖介紹

    這篇文章主要介紹了Java鎖之可重入鎖介紹,可重入鎖,也叫做遞歸鎖,指的是同一線程外層函數(shù)獲得鎖之后,內(nèi)層遞歸函數(shù)仍然有獲取該鎖的代碼,但不受影響,需要的朋友可以參考下
    2014-11-11
  • Java利用自定義注解、反射實現(xiàn)簡單BaseDao實例

    Java利用自定義注解、反射實現(xiàn)簡單BaseDao實例

    下面小編就為大家?guī)硪黄狫ava利用自定義注解、反射實現(xiàn)簡單BaseDao實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-08-08
  • 淺談JVM之類的加載鏈接和初始化

    淺談JVM之類的加載鏈接和初始化

    有了java class文件之后,為了讓class文件轉(zhuǎn)換成為JVM可以真正運行的結(jié)構(gòu),需要經(jīng)歷加載,鏈接和初始化的過程。這三個過程是怎么工作的呢?在本文中你將會找到答案。
    2021-06-06
  • Java實現(xiàn)迷你圖書管理系統(tǒng)案例全程

    Java實現(xiàn)迷你圖書管理系統(tǒng)案例全程

    這篇文章主要為大家詳細(xì)介紹了如何利用java語言實現(xiàn)簡單的圖書管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-12-12
  • SpringBoot啟動時自動執(zhí)行代碼的幾種實現(xiàn)方式

    SpringBoot啟動時自動執(zhí)行代碼的幾種實現(xiàn)方式

    這篇文章主要給大家介紹了關(guān)于SpringBoot啟動時自動執(zhí)行代碼的幾種實現(xiàn)方式,文中通過實例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2022-02-02

最新評論

体育| 齐河县| 章丘市| 灵武市| 定南县| 连州市| 闽侯县| 潢川县| 三河市| 西城区| 拉孜县| 荣昌县| 新河县| 霞浦县| 正宁县| 鸡东县| 大荔县| 安多县| 阿拉善左旗| 南部县| 大化| 丹阳市| 襄樊市| 福泉市| 个旧市| 黄骅市| 唐海县| 新余市| 岳阳市| 博乐市| 合阳县| 商南县| 梓潼县| 绥德县| 禹城市| 股票| 洱源县| 盐山县| 岐山县| 册亨县| 安义县|