一、为什么会有多线程定时任务
默认情况下,Spring Boot定时任务是按单线程方式执行的,也就是说,如果同一时刻有两个定时任务需要执行,那么只能在一个定时任务完成之后再执行下一个。如果只有一个定时任务,这样做肯定没问题;当定时任务增多时,如果一个任务被阻塞,则会导致其他任务无法正常执行。要解决这个问题,需要配置任务调度线程池。
二、如何编写多线程定时任务
1、开启定时任务:首先在主启动类上加注解
@EnableScheduling
2、通过ScheduleConfig配置文件实现SchedulingConfigurer接口,并重写setSchedulerfang方法。
package com.zkyq.obd.config.handler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import java.util.concurrent.Executors;
@Configuration
public class ScheduleConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(Executors.newScheduledThreadPool(5));
}
}
3、编写多个定时任务
@Scheduled(cron="0/1 * * * * ? ") //每1秒执行一次
public void testCron2() {
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
log.info (sdf.format(new Date())+"*********每1秒执行一次");
}
@Scheduled(cron="0/1 * * * * ? ") //每1秒执行一次
public void testCron3() {
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
log.info(sdf.format(new Date())+"*********第2秒执行一次");
}
@Scheduled(cron="0/1 * * * * ? ") //每1秒执行一次
public void testCron1() {
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
log.info (sdf.format(new Date())+"*********第3秒执行一次");
}
4、执行结果
关于多线程定时任务的使用就这些了,希望对大家有帮助。关注我,只分享干活教程!