Search code examples
javatimerejbdelay

Java EJB Calling method after a delay


I have an stateless EJB with a method that should call different methods with a delay. For example:

EJB 1

public void start()
{
   waitFor3Seconds();
   doSomething1();
   waitFor3Seconds();
   doSomething2();
   waitFor3Seconds();
   doSomething3();
}

How do I implement waitFor3Seconds() ? I don't want to use Thread.sleep() because it blocks.


Solution

  • An EJB should not wait during processing, it smells like a bad design to me. Maybe you should consider asynchronous processing? (perhaps using an MDB). And please, resist the temptation of using Thread.sleep(), that's one of the restrictions of EJB development (emphasis mine):

    Specifically, enterprise beans should not (...) create or manage threads.

    Another possibility would be to use a job scheduling framework (say, Quartz) for scheduling as many tasks as needed, setting the jobs to start one after the other at the times required by your process. In your example, three jobs would be needed: doSomething1(), doSomething2(), doSomething3(), configured to start with the required delays.