2

The following code is adapted from an example in Real-Time Java Platform Programming by Peter C. Dibble:

import javax.realtime.*;
public class OSTimer {

  static volatile boolean cont = true;

  public static void main(String[] args) {
    AsyncEventHandler handler = new AsyncEventHandler(){
        public void handleAsyncEvent() {
          System.out.println("Stopping...");
          cont = false;                  
        }
      }
    };

   OneShotTimer timer = new OneShotTimer(new RelativeTime(3000, 0), handler);
   timer.start();

   while(cont){
     System.out.println("Running");
     if (timer.isRunning()) System.out.println("Timer is running");
     try {
       Thread.sleep(1000);
     } catch(Exception e) { }
   }
   System.exit(0);
}

The the program is supposed to run for 3 seconds and then exit. However, the output shows that while the timer did indeed stop after 3 seconds, the program continues as usual, i.e. output is:

Running
Timer is running
Running
Timer is running
Running
Timer is running
Running
Running
Running......

Clearly the handler did not fire, and I've no idea why. Another example program involving a periodic timer triggering the handler does work as expected. The program structure is almost the same as the one here.

andersoj
  • 22,406
  • 7
  • 62
  • 73
wmjdgla
  • 101
  • 1
  • 8
  • is that your real code? Looks like you're missing an argument (a Clock) to your Timer constructor. (And are there any other differences with the real code?) Also, what VM are you using? – andersoj May 09 '12 at 19:30
  • whoops, scratch that, there's a `Clock`-free constructor – andersoj May 09 '12 at 19:30
  • have you tried calling `fire()` on the timer from the main thread (I know you're not supposed to). – andersoj May 09 '12 at 19:36

1 Answers1

1

A few things to try:

  1. Call fire() explicitly on the timer instance to see if you can force things
  2. Try creating your handler by passing in the logic as a Runnable object to the handler. The API is a little unclear on this, but this is how I have specified handlers in the past.

Example:

AsyncEventHandler handler = new AsyncEventHandler(new Runnable() {
    public void run() {
      System.out.println("Stopping...");
      cont = false;                  
    }
  });
andersoj
  • 22,406
  • 7
  • 62
  • 73