在這邊的範例是 [1-2] 有提到的其中一種作法,主要是利用 Spring 的 scheduled-tasks 搭配 cron expression 來控制執行時間。
首先先寫一個定時執行時要執行的類別,類別內包含某個任意名稱的方法。這個方法即是要執行的任務的內容。
1 2 3 4 5 6 7 8 9 |
package test.ExecutorTest; import java.util.Calendar; public class ExecutorTest { public void execute () { System.out.println( "Run at " + Calendar.getInstance().getTimeInMillis()); } } |
接著要在 Spring 的設定文件中加上 task 的 namespace。
1 2 3 4 5 6 7 8 9 |
主要在這個步驟真正加上的是下面這兩個屬性。
1 2 |
再來是同樣在 Spring 的設定文件上,加上關於任務的資訊,也就是完整的 XML 大約會長這樣:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
xsi:schemaLocation="http://www.springframework.org/schema/beans < bean id = "task" class = "test.ExecutorTest" /> < task:scheduled-tasks > < task:scheduled ref = "task" method = "execute" cron = "0/25 * * * * *" /> </ task:scheduled-tasks > </ beans > |
然後這樣就結束了~!
以上面設定的 cron expression 來說,執行時間是每 25 秒執行一次,因此會是每分鐘的 0 秒、25 秒和 50 秒時各執行一次。
執行結果如下:
1 2 3 4 5 6 7 8 9 10 11 |
Run at 1398312170000 Run at 1398312180000 Run at 1398312205000 Run at 1398312230000 Run at 1398312240000 Run at 1398312265000 Run at 1398312290000 Run at 1398312300001 Run at 1398312325000 Run at 1398312350000 Run at 1398312360001 |
如果需要一些常見的 cron expression 的範例,可以參考 [3]。
參考資料:
1、4 ways to schedule tasks in Spring 3 : @Scheduled example
2、Spring定时任务的几种实现
3、Cron Expression Examples
沒有留言:
張貼留言