Spring Boot 定时任务平台线程与虚拟线程不同配置

Spring Boot juc jcmd About 1,771 words

版本

Spring Boot 3.2.3

Java 代码

@Slf4j
@Component
@EnableScheduling
@EnableAsync
public class ScheduleTask {

    @Scheduled(fixedDelay = 5000)
    @Async
    public void fixedDelay() {
        log.info("fixed delay task start, name: {}, activeCount: {}", Thread.currentThread().getName(), Thread.currentThread().getThreadGroup().activeCount() );
        LockSupport.park();
        log.info("fixed delay task end, name: {}, activeCount: {}", Thread.currentThread().getName(), Thread.currentThread().getThreadGroup().activeCount() );
    }

    @Scheduled(cron = "0 0/1 * * * ?")
    @Async
    public void cron() {
        log.info("cron task, name: {}, activeCount: {}", Thread.currentThread().getName(), Thread.currentThread().getThreadGroup().activeCount() );
    }

}

说明

对于Spring Boot定时任务,基本会配置@Async异步注解,将任务交由execution线程池执行。而scheduling线程池则相当于充当调度功能,所以schedulingyaml配置并没有提供对最大线程数的限制,且scheduling.pool.size默认是1,即只需一个线程按定时时间调度给execution即可。

平台线程

对于传统的线程而言,配置execution

spring:
  task:
    execution:
      thread-name-prefix: exec-
      pool:
        core-size: 8
        max-size: 32
        keep-alive: 60s
        queue-capacity: 100
    scheduling:
      thread-name-prefix: cron-
      pool:
        size: 1

虚拟线程

pool.max-size将不起作用,取而代之的是simple.concurrency-limit限制虚拟线程最大的执行个数。如果有超过这个限制的虚拟线程同时运行,则其他虚拟线程将在队列中等待。

对于开启了虚拟线程需要额外注意,在当前发文时的版本Spring Boot 3.2.3中,如果没有使用@Async异步任务,则当有一个定时任务阻塞时,其他定时任务也将被挂起等待。(即使设置了scheduling.pool.size大于1,也会被挂起)

spring:
  threads:
    virtual:
      enabled: true
  task:
    execution:
      thread-name-prefix: exec-
      simple:
        concurrency-limit: 6
    scheduling:
      thread-name-prefix: cron-

排查挂起问题

可以使用如下命令查看线程被挂起的堆栈。

注意Thread.print可能不完整。

jcmd <pid> Thread.dump_to_file app-thread.log

更多相关文章

Spring Boot @Scheduled 定时任务

Views: 5 · Posted: 2026-01-20

———         Thanks for Reading         ———

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓
Prev Post
Today In History
Browsing Refresh