您好,欢迎访问一九零五行业门户网

SpringBoot中的Scheduled单线程执行问题怎么解决

问题描述在一次springboot中使用scheduled定时任务时,发现某一个任务出现执行占用大量资源,会导致其他任务也执行失败。
类似于以下模拟场景,test1定时任务模拟有五秒钟执行时间,这时会同步影响到test2任务的执行,导致test2任务也变成五秒执行一次。
@scheduled(fixedrate = 1000) public void test1() throws interruptedexception { log.info(thread.currentthread().getname() + " | task01 "); thread.sleep(5000); } @scheduled(fixedrate = 2000) public void test2() { log.info(thread.currentthread().getname() + " | task02 "); }
原因分析:经过相关资料查阅,发现scheduled定时任务默认的线程数只有一个,进行定时任务调度时会同步的去调度,一个执行完成后再执行另一个,这是导致该问题的直接原因。
解决方案: @bean public taskscheduler taskscheduler() { threadpooltaskscheduler taskscheduler = new threadpooltaskscheduler(); // 设置线程数量 taskscheduler.setpoolsize(50); return taskscheduler; }
添加一个配置,设置taskscheduler线程数为多个,这样再执行时就会异步执行了,各个定时任务间互不影响。
补充:使用以下java的util包中带的timertask也可以进行定时任务的执行。
以下参数中timertask是执行的任务,0表示第一次延迟0秒执行,3000表示每3000毫秒执行一次。
// true表示定时任务创建为守护线程 timer timer = new timer(true); //timer.scheduleatfixedrate(); timer.schedule(new timertask() { @override public void run() { logger.info(thread.currentthread().getname() + "************"+ftpgafileprefix); } }, 0, 3000);
以上就是springboot中的scheduled单线程执行问题怎么解决的详细内容。
其它类似信息

推荐信息