添加配置类 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