SpringBoot自带的Scheduled默认是单线程,在执行多个任务时会有等待。如果其中两个或多个的定时时间相同则其余需要等待第一个执行完成(特殊情况下有的定时任务因为冲突会不执行),这时需要创建一个线程池。

package com.cai.scheduler;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

@Configuration
@EnableScheduling
public class ScheduleConfig implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(taskExecutor());
    }

    @Bean
    public Executor taskExecutor() {
    //  线程数量
        return Executors.newScheduledThreadPool(10);
    }
}
package com.cai.scheduler;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class SchedulingThreadTest {

    @Scheduled(cron = "0 55 16 * * ?")
    public void test1() throws Exception{
        System.out.println(Thread.currentThread().getName() + "开始");
        Thread.sleep(5000);
        System.out.println(Thread.currentThread().getName() + "结束");
    }

    @Scheduled(cron = "0 55 16 * * ?")
    public void test2() throws Exception{
        System.out.println(Thread.currentThread().getName() + "开始");
        Thread.sleep(5000);
        System.out.println(Thread.currentThread().getName() + "结束");
    }
}


建议自定义线程池维护,根据定时任务动态扩容!

更多推荐

SpringBoot Schedule 配置线程池