Spring Task - Spring 原生定時任務調度
定時任務調度中,最簡單的要屬Spring原生的任務調度了吧。
過程很簡單,只需要三個步驟就可以完成。
- 準備Spring環境
這個就不用說了吧。 - 配置xml文件
添加命名空間,在xml配置文件的beans標籤中添加如下內容:xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/task/spring-task-3.0.xsd"
在beans標籤體中添加spring掃描的包,掃描需要定時執行的方法所在的類,內容如下:<context:component-scan base-package="com.test"/>
在beans標籤體中添加task標籤,內容如下:<task:executor id="executor" pool-size="5" /> <task:scheduler id="scheduler" pool-size="10" /> <task:annotation-driven executor="executor" scheduler="scheduler" />
- 添加註釋
這裏需要添加@Component和@Scheduled,@Scheduled標識要定時執行的方法,而該方法所在的類需要放入 Spring 的 IOC 容器中,故此需要在該方法所在的類上加上@Component註釋。代碼如下:package com.test; @Component public class TestClass{ // 單位毫秒 5秒執行一次 @Scheduled(fixedDelay = 5000) public void testMethod() { //... } }