springboot@scheduled启动的定时任务默认是单线程,为了满足现实生活中的使用场景,开启多个线程,方式如下:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; /** * Created by james.geng * Date: 2018\7\4 0004 */ @Configuration public class ScheduleConfig { @Bean public TaskScheduler taskScheduler() { ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); taskScheduler.setPoolSize(20); //线程池 return taskScheduler; } }
实例:
@Scheduled(cron = "0/5 * * ? * ?") public void test01() { try { log.info("s1-"+Thread.currentThread().getName()); } catch (Exception e) { e.printStackTrace(); } }
如果想用异步:
@Scheduled(cron = "0/10 * * ? * ?") @Async public void test00() { try { log.info("s01-"+Thread.currentThread().getName()); // TimeUnit.SECONDS.sleep(12); Thread.sleep(1000*20); log.info("s02-"+Thread.currentThread().getName()); } catch (Exception e) { e.printStackTrace(); } }