Question

How do I achieve a while (true) like behavior with an application server?
If I need to change my persistent data every few seconds, and with each cycle, procedures A,B,C should be called:

public class Runner
{    
    List values;

    public void repeat() 
    {
        while (true)
        {
            changeSomeDataA();
            changeSomeDataB();
            changeSomeDataC();
        }
    }
}
Was it helpful?

Solution

Use @Schedule annotation for timer service of EJB. like

  @Schedule(second="*/3", minute="*", hour="*")
  public void automaticChangeOnTimer() {
        changeSomeDataA();
        changeSomeDataB();
        changeSomeDataC();
        logger.info("Automatic called the method");
  }

For details look at following link:

http://docs.oracle.com/javaee/6/tutorial/doc/bnboy.html

OTHER TIPS

The Java EE specification provides the possibility to create EJB Timer which are useful for executing business logic at certain period of time.

Each EJB version (2.1, 3.0 , 3.1) has included changes in the form that this component can be implemented, therefore you have to search the example's code according to your java versión.

With the information provided one solution is to start a thread which sleeps say 5s before invoking the methods again, e.g.:

// init (e.g. with servlet init())
Runner r = new Runner();
Thread t = new Thread(r);
t.start();

// and later (e.g. with servlet destroy())
r.stopRunning();
t.interrupt();
t.join();

And your Runner you just need to update a little so that you can run it inside a thread.

public class Runner implements Runnable
{    
    List values;
    boolean running = true;

    public void run() 
    {
        while (running)
        {
            changeSomeDataA();
            changeSomeDataB();
            changeSomeDataC();

            try {
                Thread.sleep(5000);
            } catch(InterruptedException e) {
                // we do not really need to react here, do we?
            }
        }
    }
}

Note that you need to store the reference to the Runner and the Thread in an object (like your Servlet instance) which is not accidentally garbage collected. Of course please package nicely.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top