Spring:任務排程之task:scheduler與task:executor配置的詳解
阿新 • • 發佈:2018-11-23
其實就是Spring定時器中配置檔案中一些配置資訊,由於筆者自己是頭一次使用,有些配置詳細不太明白,隨即研究了一番,於是想記錄一下,有需要的小夥伴可以參考,也方便日後自己查閱。
首先,建立一個僅僅包含定時器配置的Spring配置檔案:spring-timer.xml。以下均為配置資訊:
1、在配置檔案頭部加入定時器的名稱空間----------
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd </beans>/
2、定時器的詳細配置----------
註解方式:
<context:annotation-config /> <!-- 自動排程需要掃描的包 --> <context:component-scan base-package="com.honest.sspc.timer" ></context:component-scan> <!-- 定時器開關 --> <task:executor id="executor" pool-size="5"/> <task:scheduler id="scheduler" pool-size="10"/> <task:annotation-driven executor="executor" scheduler="scheduler"/> xml配置方式: <context:annotation-config /> <!-- 自動排程需要掃描的包 --> <context:component-scan base-package="com.honest.sspc.timer" ></context:component-scan> <!-- 定時器開關 --> <task:executor id="executor" pool-size="5"/> <task:annotation-driven executor="executor" scheduler="scheduler"/> <!-- 配置排程 需要在類名前新增 @Service --> <task:scheduled-tasks> <task:scheduled ref="demoTask" method="myTestWork" cron="0/10 * * * * ?"/> </task:scheduled-tasks> <task:scheduler id="scheduler" pool-size="10"/> <!-- 不通過配置排程,需要在類名前 @Component/@Service,在方法名 前新增@Scheduled(cron="0/5 * * * * ? ")、即用註解的方式-->
3、關於任務排程的說明----------
任務排程器的配置詳細引數說明:
task:scheduler/@pool-size:排程執行緒池的大小,排程執行緒在被排程任務完成前不會空閒
task:scheduled/@cron:cron表示式,注意,若上次任務未完成,即使到了下一次排程時間,任務也不會重複排程
<task:scheduled-tasks scheduler="scheduler"> <task:scheduled ref="beanID" method="methodName" cron="CronExp" /> </task:scheduled-tasks> <task:scheduler id="scheduler" pool-size="1" />
任務執行器配置詳細引數說明:
task:executor/@pool-size:可以指定執行執行緒池的初始大小、最大大小
task:executor/@queue-capacity:等待執行的任務佇列的容量
task:executor/@rejection-policy:當等待佇列爆了時的策略,分為丟棄、由任務執行器直接執行等方式
<task:executor id="executor" keep-alive="3600" pool-size="100-200" queue-capacity="500" rejection-policy="CALLER_RUNS" />
原文參考:https://blog.csdn.net/weixin_37848710/article/details/79635021