Spring3的任务调度示例
?
软件环境:spring3.1.1
????实现目标:测试Spring3的任务调度使用,以及实现任务的暂停与唤醒。
Spring3对任务调度提供了更多的支持,并且提供了新的命名空间task,支持固定时间频率的任务调度和cron表达式。可以替代quartz组件来实现简单的任务调度。本文的目的是要使用spring3自带的任务调度机制实现一个简单的任务调度,并且该任务调度中提供了任务的暂停和唤醒功能。
任务类不必再继承于TimerTask,而可以是一个普通的java类,方法名可以为任意的public方法,如下。
?
public class MyTimerTask {private boolean pause = false;public void run() {synchronized (this) {if (pause) {try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}} else {print();}}}private void print() {System.out.println(new SimpleDateFormat("hh:mm:ss").format(new Date()) + " : MyTimerTask running...");}public void pause() {synchronized (this) {this.pause = true;}}public void wakeup() {synchronized (this) {this.pause = false;this.notifyAll();}}}?
? ? ? ?在该类中,提供了一个run()方法做为任务的实际执行过程,并且提供两个方法pause()和wakeup()用来暂停和唤醒任务。
3.?配置文件
在配置文件中使用了task命名空间对任务的调度进行定义,并定义了执行的周期。
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsdhttp://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd"xmlns:context="http://www.springframework.org/schema/context"xmlns:task="http://www.springframework.org/schema/task"><task:scheduler id="messageTaskScheduler" pool-size="5" /><task:scheduled-tasks scheduler="messageTaskScheduler"><task:scheduled ref="timerTask" method="run"fixed-delay="#{3*1000}" /></task:scheduled-tasks><bean id="timerTask" /></beans>?
?
测试类编写如下:
?
@ContextConfiguration(locations="classpath:applicationContext.xml")public class MyTaskTest extends AbstractJUnit4SpringContextTests {@Autowiredprivate MyTimerTask timerTask;@Testpublic void testTask() throws Exception{System.out.println(timerTask);Thread.sleep(30 * 1000);System.err.println("pause for 20 seconds...");timerTask.pause();Thread.sleep(20 * 1000);System.err.println("wakeup...");timerTask.wakeup();Thread.sleep(30 * 1000);}}?
? ? ??运行该测试用例,可以在控制台中看到如下输出:
?
10:40:50?:?MyTimerTask?running...
10:40:53?:?MyTimerTask?running...
10:40:56?:?MyTimerTask?running...
10:40:59?:?MyTimerTask?running...
10:41:02?:?MyTimerTask?running...
10:41:05?:?MyTimerTask?running...
10:41:08?:?MyTimerTask?running...
10:41:11?:?MyTimerTask?running...
10:41:14?:?MyTimerTask?running...
10:41:17?:?MyTimerTask?running...
pause?for?20?seconds...
wakeup...
10:41:41?:?MyTimerTask?running...
10:41:44?:?MyTimerTask?running...
10:41:47?:?MyTimerTask?running...
10:41:50?:?MyTimerTask?running...
10:41:53?:?MyTimerTask?running...
10:41:56?:?MyTimerTask?running...
10:41:59?:?MyTimerTask?running...
10:42:02?:?MyTimerTask?running...
10:42:05?:?MyTimerTask?running...