在一些工作需要使用到定時器,Spring很好的集成了定時器的功能!
在Spring 中使用Quartz,本文介紹Spring3.0以後自主開發的定時任務工具,spring task,可以將它比作一個輕量級的Quartz,而且使用起來很簡單,除spring相關的包外不需要額外的包,
下面介紹兩種方式實現Spring定時器功能,一種是基於xml配置方式,一種是基於註解的方式,大家根據自己的項目選擇適合自己的。
一:基於xml配置的方式
1:編寫普通的pojo 類
package com.aflyun.web.task;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
@Component
//@Service 都可以
public class TaskCool {
/**
- 第一個定時器測試方法
*/
public void testJob(){
System.out.println("test first taskJob .... ");
}
}
2:配置xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd">
<context:component-scan base-package="com.aflyun.web" />
<aop:aspectj-autoproxy proxy-target-class="true" />
<context:annotation-config />
<!-- 在applicationContext.xml中進行配置,使用定時器
ref : pojo類的名稱
method : 調用的方式名稱
cron : cronExpression表達式
cron="0/5 * * * * ?" //表示五秒鐘執行一次
-->
<task:scheduled-tasks>
<task:scheduled ref="taskCool" method="testJob" cron="0/5 * * * * ?"/>
</task:scheduled-tasks>
</beans>
注:上面主要的配置文件中一定要加入task的命名空間和schema。
上面 ref=”taskCool”,默認爲這個TaskCool 類的首字母小寫的值,若需要修改可以在@Component裏面進行修改 ,例如下面
@Component(“taskCoolJob”) 則此時 ref=”taskCoolJon”。
到此基於xml配置完成,運行則可以看到效果!
二:基於註解方式
使用註解方式不需要再每寫一個任務類還要在xml文件中配置下,方便了很多。使用Spring的@Scheduled,下面先看一註解@Scheduled在源文件中的定義:
@Target({java.lang.annotation.ElementType.METHOD, java.lang.annotation.ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Scheduled
{
public abstract String cron();
public abstract long fixedDelay();
public abstract long fixedRate();
}
cron:表示指定cron表達式。(cron類型表示 是指定時間觸發器觸發任務執行!)
fixedDelay:表示從上一個任務完成開始到下一個任務開始的間隔,單位是毫秒。
fixedRate:表示從上一個任務開始到下一個任務開始的間隔,單位是毫秒。
下面進行一下具體的配置過程:
1:編寫pojo類
package com.tclshop.cms.center.web.task;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class WebTask {
// 每五秒執行一次
@Scheduled(cron = "0/5 * * * * ?")
public void TaskJob() {
System.out.println("test second annotation style ...");
}
}
2:配置xml文件
下面貼出相關的配置文件內容: