ejb3.0學習 -- 定時服務

開發過程與session bean 大致相同。但是多了幾個操作。利用SessionContext創建定時器,並用@Timeout聲明定時器方法。
 
 @Stateless
 @Remote ({TimerService.class})
 public class TimerServiceBean implements TimerService {
  private int count = 1;
  //獲得SessionContext對象
  private @Resource SessionContext ctx;
  public void scheduleTimer(long milliseconds){
   count = 1;
   //創建定時器
   ctx.getTimerService().createTimer(new Date(new Date().getTime() + milliseconds),
   milliseconds, "大家好,這是我的第一個定時器");
  }
  @Timeout
  public void timeoutHandler(Timer timer)
  {
   System.out.println("---------------------");
   System.out.println("定時器事件發生,傳進的參數爲: " + timer.getInfo());
   System.out.println("---------------------");
   if (count>=5){
    timer.cancel();//如果定時器觸發5 次,便終止定時器
   }
   count++;
  }
 }

 public interface TimerService {
  public void scheduleTimer(long milliseconds);
 } 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章