多个@scheduled定时任务执行时个别不执行
原因
项目在启动时,如果没有指定线程池的大小,默认会创建核心线程数为1的默认线程池,故而当项目中出现多个@scheduled线程时,只能一个个的执行,从而导致个别线程执行时间过长(或长期执行)时,其他定时器不能按照指定的规则进行执行。
解决办法
1、配置执行线程池的大小
spring.task.scheduling.pool.size=10
2.将定时器设置为异步线程
/** 异步线程 定时器延迟1秒启动,每距上一次执行完成后间隔3秒执行一次 */ @async(“taskexecutor”) @scheduled(initialdelay = 1000l, fixeddelay = 3000l) public void test(){system.out.println(“—”+system.currenttimemillis());//业务内容 }
@scheduled多定时任务,重叠执行
@scheduled如果有两个定时任务,定时任务重复时,只有一个可以执行。如下
import org.springframework.scheduling.annotation.scheduled; import org.springframework.stereotype.component; import java.time.localdatetime; @component public class myscheduled { @scheduled(cron = "0/5 * * * * ?") public void execute1(){ string curname = thread.currentthread().getname() ; system.out.println("当前时间:"+localdatetime.now()+" 任务execute1对应的线程名: "+curname); try { thread.sleep(1000); } catch (exception e) { e.printstacktrace(); } } @scheduled(cron = "0/5 * * * * ?") public void execute2(){ string curname = thread.currentthread().getname() ; system.out.println("当前时间:"+localdatetime.now()+" 任务execute2对应的线程名: "+curname); try { thread.sleep(1000); } catch (interruptedexception e) { e.printstacktrace(); } } }
通过执行可以看到,打印线程名称为同一个。即如果不手动指定线程池,则默认启动单线程,进行执行定时任务。
如果想要多个定时任务重叠执行,需要手动指定线程池,如下
import org.springframework.context.annotation.bean; import org.springframework.scheduling.taskscheduler; import org.springframework.scheduling.annotation.enablescheduling; import org.springframework.scheduling.annotation.scheduled; import org.springframework.scheduling.concurrent.threadpooltaskscheduler; import org.springframework.stereotype.component; import java.time.localdatetime; @component @enablescheduling public class myscheduled { @bean public taskscheduler taskscheduler() { threadpooltaskscheduler taskscheduler = new threadpooltaskscheduler(); taskscheduler.setpoolsize(50); return taskscheduler; } @scheduled(cron = "0/5 * * * * ?") public void execute1(){ string curname = thread.currentthread().getname() ; system.out.println("当前时间:"+localdatetime.now()+" 任务execute1对应的线程名: "+curname); try { thread.sleep(1000); } catch (exception e) { e.printstacktrace(); } } @scheduled(cron = "0/5 * * * * ?") public void execute2(){ string curname = thread.currentthread().getname() ; system.out.println("当前时间:"+localdatetime.now()+" 任务execute2对应的线程名: "+curname); try { thread.sleep(1000); } catch (interruptedexception e) { e.printstacktrace(); } } }
此时,多个定时任务,是不通的线程执行,同时,定时任务可以重叠执行。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论