spring定時器的使用——schedule
阿新 • • 發佈:2018-12-12
applicationContext-schedule.xml配置:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd"> <task:annotation-driven scheduler="schedule" executor="executor"/> <!-- 在執行定時任務時最多啟用五個執行緒 --> <task:scheduler id="schedule" pool-size="5"/> <!-- 與@Async配合使用,會在排程執行緒呼叫該任務時啟用一個執行緒池,執行緒最大數為5,最小數為2,快取任務為200,多於200的拒絕策略為丟棄 --> <task:executor id="executor" pool-size="5" keep-alive="2" queue-capacity="200" rejection-policy="ABORT"/> <context:annotation-config /> <context:component-scan base-package="****"/> </beans>
applicationContext-root.xml中引入applicationContext-schedule.xml:
<import resource="classpath:applicationContext-schedule.xml" />
web.xml的配置:
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext-root.xml</param-value> </context-param>
java類中的寫法:
@Scheduled(cron = "0 0 0/5 * * ?")
void syncCaseStatus() {
System.out.println("================定時器=============");
}
總結:1.java類所在的包要跟applicationContext-schedule.xml中配置的掃描包對應。 2.spring中schedule預設是單執行緒的,要開啟多執行緒需要加上applicationContext-schedule.xml中的配置 3.注意scheduler 和executor 配置間的差別。