前言
在springboot中的@schedule默认的线程池中只有一个线程,所以如果在多个方法上加上@schedule的话,此时就会有多个任务加入到延时队列中,因为只有一个线程,所以任务只能被一个一个的执行。
如果有多个定时器,而此时有定时器运行时间过长,就会导致其他的定时器无法正常执行。
代码示例
@component public class testtimer { @scheduled(cron = "0/1 * * * * ? ") public void test01() { date date = new date(); log.info((new simpledateformat("yyyy-mm-dd hh:mm:ss").format(date) + "test01定时任务执行开始")); try { thread.sleep(3000); } catch (interruptedexception e) { throw new runtimeexception(e); } log.info((new simpledateformat("yyyy-mm-dd hh:mm:ss").format(date) + "test01定时任务执行结束")); } @scheduled(cron = "0/1 * * * * ? ") public void test02() { date date = new date(); log.info((new simpledateformat("yyyy-mm-dd hh:mm:ss").format(date) + "test02定时任务执行了")); } }
注意需要在启动类上加上@enablescheduling
输出台
2024-08-19 19:07:52.010 info 10372 --- [ scheduling-1] com.qbh.timer.testtimer : 2024-08-19 19:07:52test02定时任务执行了
2024-08-19 19:07:52.010 info 10372 --- [ scheduling-1] com.qbh.timer.testtimer : 2024-08-19 19:07:52test01定时任务执行开始
2024-08-19 19:07:55.024 info 10372 --- [ scheduling-1] com.qbh.timer.testtimer : 2024-08-19 19:07:52test01定时任务执行结束
2024-08-19 19:07:55.024 info 10372 --- [ scheduling-1] com.qbh.timer.testtimer : 2024-08-19 19:07:55test02定时任务执行了
2024-08-19 19:07:56.002 info 10372 --- [ scheduling-1] com.qbh.timer.testtimer : 2024-08-19 19:07:56test01定时任务执行开始
2024-08-19 19:07:59.016 info 10372 --- [ scheduling-1] com.qbh.timer.testtimer : 2024-08-19 19:07:56test01定时任务执行结束
2024-08-19 19:07:59.016 info 10372 --- [ scheduling-1] com.qbh.timer.testtimer : 2024-08-19 19:07:59test02定时任务执行了
2024-08-19 19:08:00.014 info 10372 --- [ scheduling-1] com.qbh.timer.testtimer : 2024-08-19 19:08:00test01定时任务执行开始
2024-08-19 19:08:03.022 info 10372 --- [ scheduling-1] com.qbh.timer.testtimer : 2024-08-19 19:08:00test01定时任务执行结束
2024-08-19 19:08:03.022 info 10372 --- [ scheduling-1] com.qbh.timer.testtimer : 2024-08-19 19:08:03test02定时任务执行了
从打印的日志也可以看出来,两个定时器共用一个线程。
此时就需要让定时器使用异步的方式进行,以下为实现方式:
使用自定义线程池实现异步代码
配置文件
thread-pool: config: core-size: 8 max-size: 16 queue-capacity: 64 keep-alive-seconds: 180
import lombok.data; import org.springframework.boot.context.properties.configurationproperties; import org.springframework.stereotype.component; /** * @author qf * @since 2024/08/20 */ @component @configurationproperties(prefix = "thread-pool.config") @data public class testthreadpoolconfig { private integer coresize; private integer maxsize; private integer queuecapacity; private integer keepaliveseconds; }
线程池
import org.springframework.beans.factory.annotation.autowired; import org.springframework.context.annotation.bean; import org.springframework.context.annotation.configuration; import org.springframework.scheduling.annotation.enableasync; import org.springframework.scheduling.concurrent.threadpooltaskexecutor; import java.util.concurrent.rejectedexecutionhandler; /** * @author qf */ @configuration @enableasync public class threadpoolconfig { @autowired private testthreadpoolconfig testthreadpoolconfig; @bean(name = "testexecutor") public threadpooltaskexecutor testthreadpoolexecutor() { return getasynctaskexecutor("test-executor-", testthreadpoolconfig.getcoresize(), testthreadpoolconfig.getmaxsize(), testthreadpoolconfig.getqueuecapacity(), testthreadpoolconfig.getkeepaliveseconds(), null); } /** * 统一异步线程池 * * @param threadnameprefix * @param corepoolsize * @param maxpoolsize * @param queuecapacity * @param keepaliveseconds * @param rejectedexecutionhandler 拒接策略 没有填null * @return */ private threadpooltaskexecutor getasynctaskexecutor(string threadnameprefix, int corepoolsize, int maxpoolsize, int queuecapacity, int keepaliveseconds, rejectedexecutionhandler rejectedexecutionhandler) { threadpooltaskexecutor taskexecutor = new threadpooltaskexecutor(); taskexecutor.setcorepoolsize(corepoolsize); taskexecutor.setmaxpoolsize(maxpoolsize); taskexecutor.setqueuecapacity(queuecapacity); taskexecutor.setthreadpriority(thread.max_priority);//线程优先级 taskexecutor.setdaemon(false);//是否为守护线程 taskexecutor.setkeepaliveseconds(keepaliveseconds); taskexecutor.setthreadnameprefix(threadnameprefix); taskexecutor.setrejectedexecutionhandler(rejectedexecutionhandler); taskexecutor.initialize();//线程池初始化 return taskexecutor; } }
定时器
import lombok.extern.slf4j.slf4j; import org.springframework.scheduling.annotation.async; import org.springframework.scheduling.annotation.scheduled; import org.springframework.stereotype.component; import java.text.simpledateformat; import java.util.date; /** * @author qf */ @slf4j @component public class testtimer { @async("testexecutor") @scheduled(cron = "0/1 * * * * ? ") public void test01() { date date = new date(); log.info((new simpledateformat("yyyy-mm-dd hh:mm:ss").format(date) + "test01定时任务执行开始")); try { thread.sleep(3000); } catch (interruptedexception e) { throw new runtimeexception(e); } log.info((new simpledateformat("yyyy-mm-dd hh:mm:ss").format(date) + "test01定时任务执行结束")); } @async("testexecutor") @scheduled(cron = "0/1 * * * * ? ") public void test02() { date date = new date(); log.info((new simpledateformat("yyyy-mm-dd hh:mm:ss").format(date) + "test02定时任务执行了")); } }
输出台结果
2024-08-20 19:33:20.020 info 4420 --- [test-executor-1] com.qbh.timer.testtimer : 2024-08-20 19:33:20test01定时任务执行开始
2024-08-20 19:33:20.020 info 4420 --- [test-executor-2] com.qbh.timer.testtimer : 2024-08-20 19:33:20test02定时任务执行了
2024-08-20 19:33:21.002 info 4420 --- [test-executor-4] com.qbh.timer.testtimer : 2024-08-20 19:33:21test02定时任务执行了
2024-08-20 19:33:21.002 info 4420 --- [test-executor-3] com.qbh.timer.testtimer : 2024-08-20 19:33:21test01定时任务执行开始
2024-08-20 19:33:22.015 info 4420 --- [test-executor-5] com.qbh.timer.testtimer : 2024-08-20 19:33:22test01定时任务执行开始
2024-08-20 19:33:22.015 info 4420 --- [test-executor-6] com.qbh.timer.testtimer : 2024-08-20 19:33:22test02定时任务执行了
2024-08-20 19:33:23.009 info 4420 --- [test-executor-7] com.qbh.timer.testtimer : 2024-08-20 19:33:23test01定时任务执行开始
2024-08-20 19:33:23.009 info 4420 --- [test-executor-8] com.qbh.timer.testtimer : 2024-08-20 19:33:23test02定时任务执行了
2024-08-20 19:33:23.025 info 4420 --- [test-executor-1] com.qbh.timer.testtimer : 2024-08-20 19:33:20test01定时任务执行结束
2024-08-20 19:33:24.003 info 4420 --- [test-executor-3] com.qbh.timer.testtimer : 2024-08-20 19:33:21test01定时任务执行结束
查看输出台可以看出定时器已经异步执行了。
但是这里会发现一个问题,可以发现当前定时器任务还没有执行完一轮,下一轮就已经开始了。
如果业务中需要用到上一次定时器的结果等情况,则会出现问题。
解决上一轮定时器任务未执行完成,下一轮就开始执行的问题
本人暂时想到的方式是通过加锁的方式,当上一轮未执行完时,下一轮阻塞等待上一轮执行。
改造定时器类
import lombok.extern.slf4j.slf4j; import org.springframework.scheduling.annotation.async; import org.springframework.scheduling.annotation.scheduled; import org.springframework.stereotype.component; import java.text.simpledateformat; import java.util.date; import java.util.concurrent.locks.reentrantlock; /** * @author qf */ @slf4j @component public class testtimer { private final reentrantlock timerlock = new reentrantlock(); @async("testexecutor") @scheduled(cron = "0/1 * * * * ? ") public void test01() { timerlock.lock(); date date = new date(); log.info((new simpledateformat("yyyy-mm-dd hh:mm:ss").format(date) + "test01定时任务执行开始")); try { thread.sleep(3000); } catch (interruptedexception e) { throw new runtimeexception(e); }finally { timerlock.unlock();//释放锁 } log.info((new simpledateformat("yyyy-mm-dd hh:mm:ss").format(date) + "test01定时任务执行结束")); } @async("testexecutor") @scheduled(cron = "0/1 * * * * ? ") public void test02() { date date = new date(); log.info((new simpledateformat("yyyy-mm-dd hh:mm:ss").format(date) + "test02定时任务执行了")); } }
输出台
2024-08-20 19:55:26.007 info 7752 --- [test-executor-1] com.qbh.timer.testtimer : 2024-08-20 19:55:26test02定时任务执行了
2024-08-20 19:55:26.007 info 7752 --- [test-executor-2] com.qbh.timer.testtimer : 2024-08-20 19:55:26test01定时任务执行开始
2024-08-20 19:55:27.004 info 7752 --- [test-executor-3] com.qbh.timer.testtimer : 2024-08-20 19:55:27test02定时任务执行了
2024-08-20 19:55:28.014 info 7752 --- [test-executor-5] com.qbh.timer.testtimer : 2024-08-20 19:55:28test02定时任务执行了
2024-08-20 19:55:29.009 info 7752 --- [test-executor-2] com.qbh.timer.testtimer : 2024-08-20 19:55:26test01定时任务执行结束
2024-08-20 19:55:29.009 info 7752 --- [test-executor-4] com.qbh.timer.testtimer : 2024-08-20 19:55:29test01定时任务执行开始
2024-08-20 19:55:29.009 info 7752 --- [test-executor-7] com.qbh.timer.testtimer : 2024-08-20 19:55:29test02定时任务执行了
2024-08-20 19:55:30.004 info 7752 --- [test-executor-1] com.qbh.timer.testtimer : 2024-08-20 19:55:30test02定时任务执行了
2024-08-20 19:55:31.015 info 7752 --- [test-executor-5] com.qbh.timer.testtimer : 2024-08-20 19:55:31test02定时任务执行了
2024-08-20 19:55:32.009 info 7752 --- [test-executor-4] com.qbh.timer.testtimer : 2024-08-20 19:55:29test01定时任务执行结束
2024-08-20 19:55:32.009 info 7752 --- [test-executor-7] com.qbh.timer.testtimer : 2024-08-20 19:55:32test02定时任务执行了
2024-08-20 19:55:32.009 info 7752 --- [test-executor-6] com.qbh.timer.testtimer : 2024-08-20 19:55:32test01定时任务执行开始
通过输出台可以看出下一轮的定时器会等待上一轮结束释放锁后才会执行。
使用schedulingconfigurer实现定时器异步调用
配置文件
import org.springframework.boot.autoconfigure.batch.batchproperties; import org.springframework.context.annotation.configuration; import org.springframework.scheduling.annotation.scheduled; import org.springframework.scheduling.annotation.schedulingconfigurer; import org.springframework.scheduling.config.scheduledtaskregistrar; import java.lang.reflect.method; import java.util.concurrent.executors; @configuration public class scheduleconfig implements schedulingconfigurer { /** * 计算出带有scheduled注解的方法数量,如果该数量小于默认池大小(20),则使用默认线程池核心数大小20。 * @param taskregistrar the registrar to be configured. */ @override public void configuretasks(scheduledtaskregistrar taskregistrar) { method[] methods = batchproperties.job.class.getmethods(); int defaultpoolsize = 20; int corepoolsize = 0; if (methods != null && methods.length > 0) { system.out.println(methods.length); for (method method : methods) { scheduled annotation = method.getannotation(scheduled.class); if (annotation != null) { corepoolsize++; } } if (defaultpoolsize > corepoolsize) { corepoolsize = defaultpoolsize; } } taskregistrar.setscheduler(executors.newscheduledthreadpool(corepoolsize)); } }
定时器类
import lombok.extern.slf4j.slf4j; import org.springframework.scheduling.annotation.async; import org.springframework.scheduling.annotation.scheduled; import org.springframework.stereotype.component; import java.text.simpledateformat; import java.util.date; import java.util.concurrent.locks.reentrantlock; /** * @author qf */ @slf4j @component public class testtimer { @scheduled(cron = "0/1 * * * * ? ") public void test01() { date date = new date(); log.info((new simpledateformat("yyyy-mm-dd hh:mm:ss").format(date) + "test01定时任务执行开始")); try { thread.sleep(3000); } catch (interruptedexception e) { throw new runtimeexception(e); } log.info((new simpledateformat("yyyy-mm-dd hh:mm:ss").format(date) + "test01定时任务执行结束")); } @scheduled(cron = "0/1 * * * * ? ") public void test02() { date date = new date(); log.info((new simpledateformat("yyyy-mm-dd hh:mm:ss").format(date) + "test02定时任务执行了")); } }
输出台结果
2024-08-20 20:18:58.002 info 24744 --- [pool-2-thread-2] com.qbh.timer.testtimer : 2024-08-20 20:18:58test01定时任务执行开始
2024-08-20 20:18:58.002 info 24744 --- [pool-2-thread-1] com.qbh.timer.testtimer : 2024-08-20 20:18:58test02定时任务执行了
2024-08-20 20:18:59.014 info 24744 --- [pool-2-thread-1] com.qbh.timer.testtimer : 2024-08-20 20:18:59test02定时任务执行了
2024-08-20 20:19:00.006 info 24744 --- [pool-2-thread-3] com.qbh.timer.testtimer : 2024-08-20 20:19:00test02定时任务执行了
2024-08-20 20:19:01.005 info 24744 --- [pool-2-thread-1] com.qbh.timer.testtimer : 2024-08-20 20:19:01test02定时任务执行了
2024-08-20 20:19:01.005 info 24744 --- [pool-2-thread-2] com.qbh.timer.testtimer : 2024-08-20 20:18:58test01定时任务执行结束
2024-08-20 20:19:02.013 info 24744 --- [pool-2-thread-3] com.qbh.timer.testtimer : 2024-08-20 20:19:02test01定时任务执行开始
以上可以看出该方法也可以实现定时器异步执行,并且当上一轮定时器没有执行完时,下一轮会等待上一轮完成后执行。
总结
在springboot中的@schedule默认的线程池中只有一个线程,当有多个定时器时,只会先执行其中的一个,其他定时器会加入到延时队列中,等待被执行。
springboot实现定时器异步的方式有
- 通过自定义线程池的方式实现异步。
- 通过实现schedulingconfigurer接口的方式实现异步。
这些仅为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论