开发者

EJB Timer Service: order of timeouts

开发者 https://www.devze.com 2023-03-03 19:39 出处:网络
I have two timeouts defined: timeout A - every 30 seconds timeout B - every 2 minutes // scheduled for timeout A (every 30sec)

I have two timeouts defined:

timeout A - every 30 seconds

timeout B - every 2 minutes

// scheduled for timeout A (every 30sec)
@Stateless
public class MyBeanA {
   (...)

   @Timeout
   public void onTimeoutA(javax.ejb.Timer timer) {
     // (...)
   }
}

// scheduled for timeout B (every 2min)
@Stateless
public class MyBeanB {
   (...)

   @Timeout
   public void onTimeoutB(javax.ejb.Timer timer) {
     // (...)
   }
}

It's easy to noti开发者_C百科ce, that after every 2 minutes, both timeouts will be fired. I'd like to make sure that in this case, timeout A will be fired before timeout B:

(30sec): timeoutA, (60sec): timeoutA, (90sec): timeoutA, (120sec): timeoutA, timeoutB

Is it possible with standard EJB (3.0) Timer Service API? My application server is JBoss.

Thanks in advance, Piotr


There is no built-in way to order timers like that. You could do it manually:

  1. Schedule a single-action timer for A in 30 seconds with info=1
  2. Schedule an interval timer for B for 120 seconds
  3. When A fires with info=1, schedule a single-action timer for A in 30 seconds with info=2
  4. When A fires with info=2, schedule a single action timer for A in 30 seconds with info=3
  5. When A fires with info=3, don't reschedule
  6. When B fires, call A, then do the work for B. Schedule a single-action timer for A in 30 seconds with info=1


Solution I used is very similar to the one given by bkail. There is one ejbTimeout() method scheduled to be fired every 30seconds. Timeout is scheduled with Serializable object containing counter:

createTimer(Date initialExpiration, long intervalDuration, Serializable info) 

Every time ejbTimeout is called, counter is increased. If it reach 3, then method which should be fired after 2 minutes is invoked, and also counter is set back to 0. It works as below:

ejbTimeout after 30sec (counter == 0): call A(); counter++;
ejbTimeout after 30sec (counter == 1): call A(); counter++;
ejbTimeout after 30sec (counter == 2): call A(); counter++;
ejbTimeout after 30sec (counter == 3): call A(); call B(); counter = 0;
0

精彩评论

暂无评论...
验证码 换一张
取 消