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

spring定時器@Scheduled異步調用方式

 更新時間:2024年11月21日 08:39:00   作者:齊 飛  
在Spring Boot中,@Schedule默認使用單線程執(zhí)行定時任務,多個定時器會按順序執(zhí)行,為實現(xiàn)異步執(zhí)行,可以通過自定義線程池或實現(xiàn)SchedulingConfigurer接口,使用自定義線程池可以保證多個定時器并發(fā)執(zhí)行

前言

在springboot中的@schedule默認的線程池中只有一個線程,所以如果在多個方法上加上@schedule的話,此時就會有多個任務加入到延時隊列中,因為只有一個線程,所以任務只能被一個一個的執(zhí)行。

如果有多個定時器,而此時有定時器運行時間過長,就會導致其他的定時器無法正常執(zhí)行。

代碼示例

@Component
public class TestTimer {

    @Scheduled(cron = "0/1 * *  * * ? ")
    public void test01()
    {
        Date date = new Date();
        log.info((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date) + "test01定時任務執(zhí)行開始"));
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        log.info((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date) + "test01定時任務執(zhí)行結束"));
    }

    @Scheduled(cron = "0/1 * *  * * ? ")
    public void test02()
    {
        Date date = new Date();
        log.info((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date) + "test02定時任務執(zhí)行了"));
    }
}

注意需要在啟動類上加上@EnableScheduling

輸出臺

2024-08-19 19:07:52.010  INFO 10372 --- [   scheduling-1] com.qbh.timer.TestTimer                  : 2024-08-19 19:07:52test02定時任務執(zhí)行了
2024-08-19 19:07:52.010  INFO 10372 --- [   scheduling-1] com.qbh.timer.TestTimer                  : 2024-08-19 19:07:52test01定時任務執(zhí)行開始
2024-08-19 19:07:55.024  INFO 10372 --- [   scheduling-1] com.qbh.timer.TestTimer                  : 2024-08-19 19:07:52test01定時任務執(zhí)行結束
2024-08-19 19:07:55.024  INFO 10372 --- [   scheduling-1] com.qbh.timer.TestTimer                  : 2024-08-19 19:07:55test02定時任務執(zhí)行了
2024-08-19 19:07:56.002  INFO 10372 --- [   scheduling-1] com.qbh.timer.TestTimer                  : 2024-08-19 19:07:56test01定時任務執(zhí)行開始
2024-08-19 19:07:59.016  INFO 10372 --- [   scheduling-1] com.qbh.timer.TestTimer                  : 2024-08-19 19:07:56test01定時任務執(zhí)行結束
2024-08-19 19:07:59.016  INFO 10372 --- [   scheduling-1] com.qbh.timer.TestTimer                  : 2024-08-19 19:07:59test02定時任務執(zhí)行了
2024-08-19 19:08:00.014  INFO 10372 --- [   scheduling-1] com.qbh.timer.TestTimer                  : 2024-08-19 19:08:00test01定時任務執(zhí)行開始
2024-08-19 19:08:03.022  INFO 10372 --- [   scheduling-1] com.qbh.timer.TestTimer                  : 2024-08-19 19:08:00test01定時任務執(zhí)行結束
2024-08-19 19:08:03.022  INFO 10372 --- [   scheduling-1] com.qbh.timer.TestTimer                  : 2024-08-19 19:08:03test02定時任務執(zhí)行了

從打印的日志也可以看出來,兩個定時器共用一個線程。

此時就需要讓定時器使用異步的方式進行,以下為實現(xiàn)方式:

使用自定義線程池實現(xiàn)異步代碼

配置文件

thread-pool:
  config:
    core-size: 8
    max-size: 16
    queue-capacity: 64
    keep-alive-seconds: 180
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @author qf
 * @since 2024/08/20
 */
@Component
@ConfigurationProperties(prefix = "thread-pool.config")
@Data
public class TestThreadPoolConfig {
    private Integer coreSize;
    private Integer maxSize;
    private Integer queueCapacity;
    private Integer keepAliveSeconds;
}

線程池

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.RejectedExecutionHandler;

/**
 * @author qf
 */
@Configuration
@EnableAsync
public class ThreadPoolConfig {

    @Autowired
    private TestThreadPoolConfig testThreadPoolConfig;

    @Bean(name = "testExecutor")
    public ThreadPoolTaskExecutor testThreadPoolExecutor() {
        return getAsyncTaskExecutor("test-Executor-", testThreadPoolConfig.getCoreSize(),
                testThreadPoolConfig.getMaxSize(), testThreadPoolConfig.getQueueCapacity(),
                testThreadPoolConfig.getKeepAliveSeconds(), null);
    }

    /**
     * 統(tǒng)一異步線程池
     *
     * @param threadNamePrefix
     * @param corePoolSize
     * @param maxPoolSize
     * @param queueCapacity
     * @param keepAliveSeconds
     * @param rejectedExecutionHandler 拒接策略 沒有填null
     * @return
     */
    private ThreadPoolTaskExecutor getAsyncTaskExecutor(String threadNamePrefix, int corePoolSize, int maxPoolSize, int queueCapacity, int keepAliveSeconds, RejectedExecutionHandler rejectedExecutionHandler) {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(corePoolSize);
        taskExecutor.setMaxPoolSize(maxPoolSize);
        taskExecutor.setQueueCapacity(queueCapacity);
        taskExecutor.setThreadPriority(Thread.MAX_PRIORITY);//線程優(yōu)先級
        taskExecutor.setDaemon(false);//是否為守護線程
        taskExecutor.setKeepAliveSeconds(keepAliveSeconds);
        taskExecutor.setThreadNamePrefix(threadNamePrefix);
        taskExecutor.setRejectedExecutionHandler(rejectedExecutionHandler);
        taskExecutor.initialize();//線程池初始化
        return taskExecutor;
    }
}

定時器

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author qf
 */
@Slf4j
@Component
public class TestTimer {

    @Async("testExecutor")
    @Scheduled(cron = "0/1 * *  * * ? ")
    public void test01() {
        Date date = new Date();
        log.info((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date) + "test01定時任務執(zhí)行開始"));
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        log.info((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date) + "test01定時任務執(zhí)行結束"));
    }

    @Async("testExecutor")
    @Scheduled(cron = "0/1 * *  * * ? ")
    public void test02() {
        Date date = new Date();
        log.info((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date) + "test02定時任務執(zhí)行了"));
    }
}

輸出臺結果

2024-08-20 19:33:20.020  INFO 4420 --- [test-Executor-1] com.qbh.timer.TestTimer                  : 2024-08-20 19:33:20test01定時任務執(zhí)行開始
2024-08-20 19:33:20.020  INFO 4420 --- [test-Executor-2] com.qbh.timer.TestTimer                  : 2024-08-20 19:33:20test02定時任務執(zhí)行了
2024-08-20 19:33:21.002  INFO 4420 --- [test-Executor-4] com.qbh.timer.TestTimer                  : 2024-08-20 19:33:21test02定時任務執(zhí)行了
2024-08-20 19:33:21.002  INFO 4420 --- [test-Executor-3] com.qbh.timer.TestTimer                  : 2024-08-20 19:33:21test01定時任務執(zhí)行開始
2024-08-20 19:33:22.015  INFO 4420 --- [test-Executor-5] com.qbh.timer.TestTimer                  : 2024-08-20 19:33:22test01定時任務執(zhí)行開始
2024-08-20 19:33:22.015  INFO 4420 --- [test-Executor-6] com.qbh.timer.TestTimer                  : 2024-08-20 19:33:22test02定時任務執(zhí)行了
2024-08-20 19:33:23.009  INFO 4420 --- [test-Executor-7] com.qbh.timer.TestTimer                  : 2024-08-20 19:33:23test01定時任務執(zhí)行開始
2024-08-20 19:33:23.009  INFO 4420 --- [test-Executor-8] com.qbh.timer.TestTimer                  : 2024-08-20 19:33:23test02定時任務執(zhí)行了
2024-08-20 19:33:23.025  INFO 4420 --- [test-Executor-1] com.qbh.timer.TestTimer                  : 2024-08-20 19:33:20test01定時任務執(zhí)行結束
2024-08-20 19:33:24.003  INFO 4420 --- [test-Executor-3] com.qbh.timer.TestTimer                  : 2024-08-20 19:33:21test01定時任務執(zhí)行結束

查看輸出臺可以看出定時器已經(jīng)異步執(zhí)行了。

但是這里會發(fā)現(xiàn)一個問題,可以發(fā)現(xiàn)當前定時器任務還沒有執(zhí)行完一輪,下一輪就已經(jīng)開始了

如果業(yè)務中需要用到上一次定時器的結果等情況,則會出現(xiàn)問題。

解決上一輪定時器任務未執(zhí)行完成,下一輪就開始執(zhí)行的問題

本人暫時想到的方式是通過加鎖的方式,當上一輪未執(zhí)行完時,下一輪阻塞等待上一輪執(zhí)行。

改造定時器類

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author qf
 */
@Slf4j
@Component
public class TestTimer {

    private final ReentrantLock timerLock = new ReentrantLock();
    @Async("testExecutor")
    @Scheduled(cron = "0/1 * *  * * ? ")
    public void test01() {
        timerLock.lock();
        Date date = new Date();
        log.info((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date) + "test01定時任務執(zhí)行開始"));
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            timerLock.unlock();//釋放鎖
        }
        log.info((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date) + "test01定時任務執(zhí)行結束"));
    }

    @Async("testExecutor")
    @Scheduled(cron = "0/1 * *  * * ? ")
    public void test02() {
        Date date = new Date();
        log.info((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date) + "test02定時任務執(zhí)行了"));
    }
}

輸出臺

2024-08-20 19:55:26.007  INFO 7752 --- [test-Executor-1] com.qbh.timer.TestTimer                  : 2024-08-20 19:55:26test02定時任務執(zhí)行了
2024-08-20 19:55:26.007  INFO 7752 --- [test-Executor-2] com.qbh.timer.TestTimer                  : 2024-08-20 19:55:26test01定時任務執(zhí)行開始
2024-08-20 19:55:27.004  INFO 7752 --- [test-Executor-3] com.qbh.timer.TestTimer                  : 2024-08-20 19:55:27test02定時任務執(zhí)行了
2024-08-20 19:55:28.014  INFO 7752 --- [test-Executor-5] com.qbh.timer.TestTimer                  : 2024-08-20 19:55:28test02定時任務執(zhí)行了
2024-08-20 19:55:29.009  INFO 7752 --- [test-Executor-2] com.qbh.timer.TestTimer                  : 2024-08-20 19:55:26test01定時任務執(zhí)行結束
2024-08-20 19:55:29.009  INFO 7752 --- [test-Executor-4] com.qbh.timer.TestTimer                  : 2024-08-20 19:55:29test01定時任務執(zhí)行開始
2024-08-20 19:55:29.009  INFO 7752 --- [test-Executor-7] com.qbh.timer.TestTimer                  : 2024-08-20 19:55:29test02定時任務執(zhí)行了
2024-08-20 19:55:30.004  INFO 7752 --- [test-Executor-1] com.qbh.timer.TestTimer                  : 2024-08-20 19:55:30test02定時任務執(zhí)行了
2024-08-20 19:55:31.015  INFO 7752 --- [test-Executor-5] com.qbh.timer.TestTimer                  : 2024-08-20 19:55:31test02定時任務執(zhí)行了
2024-08-20 19:55:32.009  INFO 7752 --- [test-Executor-4] com.qbh.timer.TestTimer                  : 2024-08-20 19:55:29test01定時任務執(zhí)行結束
2024-08-20 19:55:32.009  INFO 7752 --- [test-Executor-7] com.qbh.timer.TestTimer                  : 2024-08-20 19:55:32test02定時任務執(zhí)行了
2024-08-20 19:55:32.009  INFO 7752 --- [test-Executor-6] com.qbh.timer.TestTimer                  : 2024-08-20 19:55:32test01定時任務執(zhí)行開始

通過輸出臺可以看出下一輪的定時器會等待上一輪結束釋放鎖后才會執(zhí)行。

使用SchedulingConfigurer實現(xiàn)定時器異步調用

配置文件

import org.springframework.boot.autoconfigure.batch.BatchProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.lang.reflect.Method;
import java.util.concurrent.Executors;

@Configuration
public class ScheduleConfig implements SchedulingConfigurer {

    /**
     * 計算出帶有Scheduled注解的方法數(shù)量,如果該數(shù)量小于默認池大?。?0),則使用默認線程池核心數(shù)大小20。
     * @param taskRegistrar the registrar to be configured.
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        Method[] methods = BatchProperties.Job.class.getMethods();
        int defaultPoolSize = 20;
        int corePoolSize = 0;
        if (methods != null && methods.length > 0) {
            System.out.println(methods.length);
            for (Method method : methods) {
                Scheduled annotation = method.getAnnotation(Scheduled.class);
                if (annotation != null) {
                    corePoolSize++;
                }
            }
            if (defaultPoolSize > corePoolSize) {
                corePoolSize = defaultPoolSize;
            }
        }
        taskRegistrar.setScheduler(Executors.newScheduledThreadPool(corePoolSize));
    }
}

定時器類

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author qf
 */
@Slf4j
@Component
public class TestTimer {

    @Scheduled(cron = "0/1 * *  * * ? ")
    public void test01() {
        Date date = new Date();
        log.info((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date) + "test01定時任務執(zhí)行開始"));
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        log.info((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date) + "test01定時任務執(zhí)行結束"));
    }

    @Scheduled(cron = "0/1 * *  * * ? ")
    public void test02() {
        Date date = new Date();
        log.info((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date) + "test02定時任務執(zhí)行了"));
    }
}

輸出臺結果

2024-08-20 20:18:58.002  INFO 24744 --- [pool-2-thread-2] com.qbh.timer.TestTimer                  : 2024-08-20 20:18:58test01定時任務執(zhí)行開始
2024-08-20 20:18:58.002  INFO 24744 --- [pool-2-thread-1] com.qbh.timer.TestTimer                  : 2024-08-20 20:18:58test02定時任務執(zhí)行了
2024-08-20 20:18:59.014  INFO 24744 --- [pool-2-thread-1] com.qbh.timer.TestTimer                  : 2024-08-20 20:18:59test02定時任務執(zhí)行了
2024-08-20 20:19:00.006  INFO 24744 --- [pool-2-thread-3] com.qbh.timer.TestTimer                  : 2024-08-20 20:19:00test02定時任務執(zhí)行了
2024-08-20 20:19:01.005  INFO 24744 --- [pool-2-thread-1] com.qbh.timer.TestTimer                  : 2024-08-20 20:19:01test02定時任務執(zhí)行了
2024-08-20 20:19:01.005  INFO 24744 --- [pool-2-thread-2] com.qbh.timer.TestTimer                  : 2024-08-20 20:18:58test01定時任務執(zhí)行結束
2024-08-20 20:19:02.013  INFO 24744 --- [pool-2-thread-3] com.qbh.timer.TestTimer                  : 2024-08-20 20:19:02test01定時任務執(zhí)行開始

以上可以看出該方法也可以實現(xiàn)定時器異步執(zhí)行,并且當上一輪定時器沒有執(zhí)行完時,下一輪會等待上一輪完成后執(zhí)行。

總結

在Springboot中的@schedule默認的線程池中只有一個線程,當有多個定時器時,只會先執(zhí)行其中的一個,其他定時器會加入到延時隊列中,等待被執(zhí)行。

Springboot實現(xiàn)定時器異步的方式有

  1. 通過自定義線程池的方式實現(xiàn)異步。
  2. 通過實現(xiàn)SchedulingConfigurer接口的方式實現(xiàn)異步。

這些僅為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

  • jdk中String類設計成final的原由

    jdk中String類設計成final的原由

    為什么jdk中把 String 類設計成final,主要是為了“ 效率 ”和“安全性”的緣故,若 String 允許被繼承, 由于它的高度被使用率, 可能會降低程序的性能,所以String被定義成final,需要了解的朋友可以參考下
    2013-01-01
  • java中使用url進行編碼和解碼

    java中使用url進行編碼和解碼

    這篇文章主要介紹了java中使用url進行編碼和解碼,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-08-08
  • request如何獲取body的json數(shù)據(jù)

    request如何獲取body的json數(shù)據(jù)

    這篇文章主要介紹了request如何獲取body的json數(shù)據(jù)操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • spring單例如何改多例

    spring單例如何改多例

    這篇文章主要介紹了spring單例如何改多例,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • 如何用120行Java代碼寫一個自己的區(qū)塊鏈

    如何用120行Java代碼寫一個自己的區(qū)塊鏈

    這篇文章就是幫助你使用 Java 語言來實現(xiàn)一個簡單的區(qū)塊鏈,用不到 120 行代碼來揭示區(qū)塊鏈的原理,感興趣的就一起來了解一下
    2019-06-06
  • 使用filebeat收集并解析springboot日志過程示例

    使用filebeat收集并解析springboot日志過程示例

    這篇文章主要為大家介紹了使用filebeat收集并解析springboot日志實現(xiàn)過程示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-08-08
  • Java多線程之簡單模擬售票功能

    Java多線程之簡單模擬售票功能

    這篇文章主要介紹了Java多線程之簡單模擬售票功能,文中有非常詳細的代碼示例,對正在學習java的小伙伴們有很好地幫助,需要的朋友可以參考下
    2021-04-04
  • 一文吃透Spring?Cloud?gateway自定義錯誤處理Handler

    一文吃透Spring?Cloud?gateway自定義錯誤處理Handler

    這篇文章主要為大家介紹了一文吃透Spring?Cloud?gateway自定義錯誤處理Handler方法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-03-03
  • Maven中的profiles使用及說明

    Maven中的profiles使用及說明

    這篇文章主要介紹了Maven中的profiles使用及說明,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2025-06-06
  • Java調用打印機的2種方式舉例(無驅/有驅)

    Java調用打印機的2種方式舉例(無驅/有驅)

    我們平時使用某些軟件或者在超市購物的時候都會發(fā)現(xiàn)可以使用打印機進行打印,這篇文章主要給大家介紹了關于Java調用打印機的2種方式,分別是無驅/有驅的相關資料,需要的朋友可以參考下
    2023-11-11

最新評論

独山县| 汉沽区| 呼和浩特市| 河曲县| 三台县| 宁武县| 班玛县| 宜州市| 资源县| 揭东县| 洛川县| 宣恩县| 巴东县| 长治市| 斗六市| 运城市| 同德县| 汉源县| 合江县| 南岸区| 和龙市| 乐都县| 云阳县| 山东省| 牙克石市| 广德县| 鄂托克旗| 澄迈县| 乐清市| 隆尧县| 万州区| 深州市| 三亚市| 中超| 永兴县| 黑河市| 外汇| 无棣县| 玉屏| 博爱县| 宁阳县|