Spring Boot 配置Scheduler定时调度任务线程池

添加配置类 SchedulerConfig


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

@Configuration
public class SchedulerConfig {

    // 配置任务线程池,用于定时调度
    @Bean
    public ThreadPoolTaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(30); // 设置线程池大小为30
        scheduler.setThreadNamePrefix("my-task-scheduler-"); // 设置线程名称前缀
        return scheduler;
    }
}

添加测试类


import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import java.time.LocalTime;

@Slf4j
@Configuration
public class TestScheduled {

    @Scheduled(fixedDelay = 500)
    public void test() {
        log.info("thread: {} current time: {}", Thread.currentThread(), LocalTime.now());
    }
}

日志输出,线程名称正确,也切换过其他线程执行

thread: Thread[#58,my-task-scheduler-1,5,main] current time: 15:50:32.681416
thread: Thread[#58,my-task-scheduler-1,5,main] current time: 15:50:33.183829
thread: Thread[#60,my-task-scheduler-2,5,main] current time: 15:50:33.691242
thread: Thread[#58,my-task-scheduler-1,5,main] current time: 15:50:34.193585
thread: Thread[#65,my-task-scheduler-3,5,main] current time: 15:50:34.703058
thread: Thread[#60,my-task-scheduler-2,5,main] current time: 15:50:35.209871
thread: Thread[#66,my-task-scheduler-4,5,main] current time: 15:50:35.718819
thread: Thread[#58,my-task-scheduler-1,5,main] current time: 15:50:36.226740
thread: Thread[#67,my-task-scheduler-5,5,main] current time: 15:50:36.731344
thread: Thread[#65,my-task-scheduler-3,5,main] current time: 15:50:37.236365
thread: Thread[#68,my-task-scheduler-6,5,main] current time: 15:50:37.740146
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值