本文介绍Spring3.0以后自主开发的定时任务工具,spring task,可以将它比作一个轻量级的Quartz,而且使用起来很简单,除spring相关的包外不需要额外的包,而且支持注解和配置文件两种。
方式一:使用配置文件
1.编写作业类,不需要继承任何类或实现任何接口
package com.Solin.Timer;
import java.util.Date;
public class SpringTimerTest {
public void say() {
System.out.println("这个真好用!!!" + new Date());
}
public void hello(){
System.out.println("hello!!!");
}
}
2.在spring配置文件头中添加命名空间及描述
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd ">
3.spring配置文件中设置具体的任务
<!-- 注册bean -->
<bean id="springTimerTest" class="com.Solin.Timer.SpringTimerTest"></bean>
<!-- 开启任务调度 -->
<task:scheduled-tasks>
<!-- 这里表示的是从第五秒开始 ,每三秒执行一次 (而不是 三分之五 秒执行一次哦~~) -->
<task:scheduled ref="springTimerTest" method="say" cron="5/3 * * * * ?" />
<task:scheduled ref="springTimerTest" method="hello" cron="5/3 * * * * ?"/>
</task:scheduled-tasks>
说明:ref参数指定的即任务类,method指定的即需要运行的方法,cron是表达式,表示在什么时候进行任务调度。
这个真好用!!!Fri Nov 04 14:45:59 CST 2016
hello!!!
hello!!!
这个真好用!!!Fri Nov 04 14:46:05 CST 2016
hello!!!
这个真好用!!!Fri Nov 04 14:46:08 CST 2016
方式二:使用注解形式
1.编写作业类,不需要继承任何类或实现任何接口
package com.Solin.Timer;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class SpringTimerTest {
@Scheduled(cron="0/5 * * * * ? ") //每5秒执行一次
public void myTest(){
System.out.println("进入测试 " + new Date());
}
}
2.在spring配置文件头中添加命名空间及描述
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd ">
3.spring配置文件具体配置
<!-- 组件扫描 -->
<context:component-scan base-package="com.Solin.Timer" />
<!-- 定时器开关-->
<task:annotation-driven />
配置完毕,当然spring task还有很多参数,我就不一一解释了,具体参考xsd文档:http://www.springframework.org/schema/task/spring-task-3.2.xsd
4.启动项目,输出信息:
进入测试 Fri Nov 04 15:09:30 CST 2016
进入测试 Fri Nov 04 15:09:35 CST 2016
进入测试 Fri Nov 04 15:09:40 CST 2016
进入测试 Fri Nov 04 15:09:45 CST 2016
进入测试 Fri Nov 04 15:09:50 CST 2016