Spring task 定時任務的兩種用法(時間設定在.xml裡或者在 @註解裡)
阿新 • • 發佈:2019-02-18
spring 4.1.7
jdk1.8
1.時間設定在javaBean的@註解裡
spring-task.xml:
<?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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd" default-lazy-init="false"> <!-- 定時器開關 --> <task:annotation-driven /> <!-- 掃描mytask包下的檔案 --> <context:component-scan base-package="com.test.mytask" /> </beans>
javaBean:
package com.test.mytask;
import java.util.List;
@Component("test")
public class Test{
@Scheduled(cron = "*/5 * * * * ?")
public void testMethod(){
System.out.println("每5秒顯示一次,"+new Date());
}
}--------------------------------------------------------------------------
2.時間設定在spring-task.xml裡
spring-task:
<?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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd" default-lazy-init="false"> <!-- 此處和另一個方法用到註解不一樣,不必有driver--> <context:annotation-config /> <!-- 掃描mytask包下的檔案 --> <context:component-scan base-package="com.test.mytask" /> <bean id="Test" class="com.test.mytask.Test" /> <task:scheduled-tasks> <task:scheduled ref="Test" method="testMethos" cron="*/5 * * * * ?" /> </task:scheduled-tasks> </beans>
javaBean:
package com.test.mytask;
import java.util.Date;
@Component("Test")
public class Test{
@Scheduled
public void testMethod(){
System.out.println("每5秒顯示一次,"+new Date());
}
}
比較:
在@scheduled註解中寫時間設定,不用太多的配置xml ;
但是在xml配置檔案中寫時間設定方便別人修改和管理,建議採用xml中設定時間的方法