ejb3.0定時執行任務 ejb3提供了,定時執行某項任務的功能實現步驟:1 . 建立一個sessionbean 和對應的介面 這個沒什麼特殊,跟以往一樣2. 擷取一個sessionContext對象3 . 在sessionContext中get到TimerService4. 在TimeService中擷取到Timer對象,建立該對象時候第一個參數代表定時任務開始執行的時間(精確到毫秒),第二個參數代表建個多久,第三個為傳入的參數(這個參數在執行任務的時候可以取到)5.寫一個方法,名稱規則為public xxx(Timer timer)6. 用annotation Timeout修飾這個方法 代碼實現
package com.foshanshop.ejb3.timer;
public
interface TimerService{
public
void scheduleTimer(
long milliseconds);}
package com.foshanshop.ejb3.timer;
import java.util.Date;
import javax.annotation.Resource;
import javax.ejb.Remote;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.ejb.Timeout;
import javax.ejb.Timer; @Stateless@Remote({TimerService.
class})
public
class TimerServiceBean
implements TimerService{
intcount = 0;
public@Resource SessionContext sctx;
public
void scheduleTimer(
long milliseconds) { sctx.getTimerService().createTimer(
new Date(
new Date().getTime()+milliseconds),milliseconds,"我的第一個定時器"); System.
out.println("begin"); } @Timeout
public
void timeoutHandler(Timer time) { System.
out.println("定時器發生"+time.getInfo()); count++;
if(count>5) time.cancel(); }
public SessionContext getSctx() {
returnsctx; }
public
void setSctx(SessionContext sctx) {
this.sctx = sctx; } } 執行結果11:03:15,750 INFO [STDOUT] begin11:03:16,750 INFO [STDOUT] 定時器發生我的第一個定時器11:03:17,765 INFO [STDOUT] 定時器發生我的第一個定時器11:03:18,750 INFO [STDOUT] 定時器發生我的第一個定時器11:03:19,750 INFO [STDOUT] 定時器發生我的第一個定時器11:03:20,750 INFO [STDOUT] 定時器發生我的第一個定時器11:03:21,750 INFO [STDOUT] 定時器發生我的第一個定時器