EJB 3.0(Public Draft)入門記 Simplified API Chapter 10 その4 Timeout

今回はTimeoutアノテーションです。「Simplified API」ドキュメントで言えば10.8節です。

どのように説明されているかというと、TimeoutアノテーションエンタープライズBeanのtimeoutメソッドを示すために使用します。ってこれだけしか書いてない…。
定義も

@Target({METHOD}) @Retention(RUNTIME)
public @interface Timeout{}

と、いたってシンプル。
これだけじゃぜんぜん使い方がわからなかいんですけど...

でも、JBossのサンプル見たらなんとなくわかりました。Timeoutアノテーションはコールバックされるメソッドにつけるアノテーションなんですね。それと、Timer関係の仕組みってEJB 2.1からあるんですね。いままで一度も使ったことありませんでした。一般的には使われている機能なんでしょうか?

JBossのサンプルを参考にTimeoutアノテーションを使って何か動くものを作ってみました(JBossのサンプルとほぼ同じという話も)。
ビジネスインタフェース

public interface Scheduler {
  void schedule(long duration);
}

Beanクラス:Timeoutアノテーションつかってます。

@Stateless
@Remote(Scheduler.class)
public class SchedulerBean implements Scheduler {
  
  @Resource
  private SessionContext ctx; 
  
  public void schedule(long duration) {
    ctx.getTimerService().createTimer(duration, "Hello!");
  }
  
  @Timeout
  public void timeout(Timer t) {
    System.out.println(t.getInfo());
    t.cancel();
  }
}

クライアント

public class SchedulerClient {
  public static void main(String[] args) throws Exception {
    InitialContext ctx = new InitialContext();
    Scheduler scheduler = (Scheduler)ctx.lookup(Scheduler.class.getName());
    scheduler.schedule(10000);
  }
}

デプロイしてクライアントを動かすと10秒くらいたってJBossコンソールに「Hello!」と表示されました。とりあえずOK!

chapter 10 その4 終わり。