Cosminexus V9 アプリケーションサーバ 機能解説 基本・開発編(EJBコンテナ)
Timer Serviceを使用する場合のアプリケーションの実装内容として,APIを使用した実装と,アノテーションを使用した実装について説明します。また,カレンダー形式でスケジュールを指定する場合の指定方法についても説明します。
次の内容を実装します。
これらの処理を実装した例と,実装時の注意事項を示します。
アノテーションを使用した場合の実装例を示します。この例では,Timeoutアノテーション(@Timeout)でタイムアウトメソッド(myTimeout)を指定しています。
@Stateless public class TimerSessionBean{
@Resource TimerService timerService;
public void createMyTimer(long intervalDuration){
Timer timer = timerService.createTimer
(intervalDuration, "MyTimer");
}
@Timeout public void myTimeout(Timer timer) {
System.out.println("TimerSessionBean: myTimeout ");
}
public void cancelTimers(){
Collection<Timer> timers = timerService.getTimers();
for(Timer timer: timers) {
timer.cancel();
}
}
}
|
EJBContextのサブクラスであるSessionContextを利用して,TimerServiceオブジェクトを取得する例を示します。この例では,TimedObjectインタフェースをインプリメントして実装しています。
public class TimerSessionBean implements SessionBean, TimedObject{
private SessionContext context;
public void createMyTimer(long intervalDuration) {
System.out.println("TimerSessionBean: start createTimer ");
TimerService timerService = context.getTimerService();
Timer timer = timerService.createTimer
(intervalDuration, "MyTimer");
}
public void ejbTimeout(Timer timer) {
System.out.println("TimerSessionBean: ejbTimeout ");
}
public void setSessionContext(SessionContext sc) {
context = sc;
}
}
|
JNDIを使用して,TimerServiceオブジェクトを取得する例を示します。この例では,TimedObjectインタフェースをインプリメントして実装しています。
public class TimerSessionBean implements SessionBean, TimedObject{
private SessionContext context;
public void createMyTimer(long intervalDuration) {
System.out.println("TimerSessionBean: start createTimer ");
InitialContext context = new InitialContext();
TimerService timerService =
(TimerService)context.lookup("java:comp/TimerService");
Timer timer = timerService.createTimer
(intervalDuration, "MyTimer");
}
public void ejbTimeout(Timer timer){
System.out.println("TimerSessionBean: ejbTimeout ");
}
}
|
@Scheduleアノテーションを使用して,タイマを自動生成できます。
例を示します。
@Scheduleアノテーションを指定する例を示します。この例では,一つのタイマを生成します。
// @Scheduleアノテーションで毎月1日1時に
// generateMonthlyAccountStatementsメソッドを実行する設定の例です。
@Schedule(hour="1", dayOfMonth="1",info="AccountStatementTimer")
public void generateMonthlyAccountStatements() { ... }
|
@Scheduleアノテーションのinfo属性には,任意の文字列を指定します。指定された文字列は,関連するTimerオブジェクトのgetInfoメソッドで取得できます。
@Schedulesアノテーションを指定する例を示します。この例では,複数のタイマを生成します。
// @Schedulesアノテーションで月曜日〜木曜日の12時と
// 金曜日の11時にsendLunchNotificationメソッドを実行する設定の例です。
@Schedules (
{ @Schedule(hour="12", dayOfWeek="Mon-Thu"),
@Schedule(hour="11", dayOfWeek="Fri")
}
)
public void sendLunchNotification() { ... }
|
@Schedulesアノテーションを使用することで,複数のタイマが一つのコールバックメソッドから呼び出されます。
カレンダー形式のコーディングでは次のように値を使用します。
なお,指定できる値などは,標準仕様に準拠しています。
All Rights Reserved. Copyright (C) 2012, 2015, Hitachi, Ltd.