首先,配置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控制台输出结果: