首先,配置maven的pom.xml:
<!-- 定時任務 -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
然後,在spring-service.xml中,添加配置文件頭部:
xmlns:task="http://www.springframework.org/schema/task"
在xsi:schemaLocation,添加:
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd
在spring-service.xml中的配置信息:
<!-- 啓動定時任務的時候需要,掃描task包 -->
<context:component-scan base-package="com.text.task" />
<!-- 設置動作啓用定時任務 -->
<task:annotation-driven/>
在com.text.task包中,設置任務類,添加註解:
package com.text.task;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class Test {
@Scheduled(cron = "*/5 * * * * ?")//每隔5秒執行一次
public void test() throws Exception{
System.out.println("------------------------------sms msg has working!");
}
}
運行Tomcat,Eclipse控制檯輸出結果: