做到數據統計相關的問題,還有商品有關自動上架等功能,需要每天定時獲取商品的瀏覽記錄,收藏記錄以及下單數量等等,需要使用定時任務來處理。想到spring自帶的定時任務比較簡單,就用<task:annotation-driven /> 來解決。
1.首先定義一個定時操作:
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
public class Singer {
//@Scheduled(fixedDelay=1000) //第一種方式
//fixedDelay延時多少毫秒執行一次(方法執行完畢後延遲)
//@Scheduled(fixedRate=1000)//第二種方式
//fixedRate每隔多少毫秒執行一次(不用等待方法執行完畢,每隔相應時間便執行)
@Scheduled(cron="0 * * * * *") //第三種方式
//corn傳入7個參數,分別是:秒,分,時,月份的日期,月份,星期幾,年(指定時間來執行:0 * * * * *表示每隔1分鐘就執行一次)
/* 日期參數詳解
1 Seconds (0-59)
2 Minutes (0-59)
3 Hours (0-23)
4 Day of month (1-31)
5 Month (1-12 or JAN-DEC)
6 Day of week (1-7 or SUN-SAT)
7 Year (1970-2099)
取值:可以是單個值,如6;
也可以是個範圍,如9-12;
也可以是個列表,如9,11,13
也可以是任意取值,使用*
*/
public void singing(){ //定時打印時間功能(每隔一分鐘)
Date date=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println(sdf.format(date));
}
}
2.Spring配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd ">
<!—開啓這個配置,spring才能識別@Scheduled註解 -->
<task:annotation-driven />
</beans>
ok,然後重新啓動eclipse,在控制檯就會看到定時執行的輸出日期任務在執行了。