這裏我們將的是記住配置文件完成的springTask 的定時任務,首先我們這邊看applicationspringtask.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 基於springtask配置文件完成定時任務-->
<!-- 開啓註解-->
<!-- <task:annotation-driven></task:annotation-driven>-->
<!-- 任務類-->
<bean id="myTask" class="com.springtask.MyTask"/>
<!-- 定時任務的定時列表:
注:每個子標籤都是一個定時任務
ref: 任務類
method: 任務類中的任務方法的名稱
fixed-delay:固定的出發頻率 單位:mm 1m=1000mm
-->
<task:scheduled-tasks>
<task:scheduled ref="myTask" method="m1" fixed-delay="10000"/>
</task:scheduled-tasks>
</beans>
任務的實現類:這個任務實現類不需要繼承任何的類,這裏的任務類和任務方法都是隨意的
此處,我簡單的寫個打印系統時間的就ok了
package com.springtask;
import java.util.Date;
/**
* @Author :MrYu
* @Description : 基於配置文件的任務類
* 創建時間 :2019/5/26 on 4:21
*/
public class MyTask {
public void m1() {
System.out.println(new Date());
}
}
以上就算是完成的定時任務:不明白的可以詳細的看我的註解,先從上往下看,先看配置文件
接下來我們測試下:下面是測試用例
注意:不能用@Test測試,完全測試不出來效果的
package com.springtask;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @Author :MrYu
* @Description : 基於spring的springtask的定時任務
* 注意:不能用@Test測試,完全測試不出來效果的
* 創建時間 :2019/5/26 on 4:28
*/
public class TestSpringTask {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring/applicationtask.xml");
}
}
測試結果:
[ INFO ] - [ org.springframework.context.support.AbstractApplicationContext.prepareRefresh(AbstractApplicationContext.java:513) ] Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4926097b: startup date [Sun May 26 04:50:43 CST 2019]; root of context hierarchy
[ INFO ] - [ org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:316) ] Loading XML bean definitions from class path resource [spring/applicationtask.xml]
Sun May 26 04:50:43 CST 2019
Sun May 26 04:50:53 CST 2019
Sun May 26 04:51:03 CST 2019
Sun May 26 04:51:13 CST 2019
Sun May 26 04:51:23 CST 2019
Sun May 26 04:51:33 CST 2019
Sun May 26 04:51:43 CST 2019
Sun May 26 04:51:53 CST 2019
Sun May 26 04:52:03 CST 2019