Example index

Scheduling UM Timers

Ultra Messaging has a feature where developers can schedule timer function callbacks via the API, where the desired function is executed in a desired number of milliseconds from when it was scheduled. The callback itself must be created by the developer, and it is executed by the UM context thread or via a UM Event Queue, if an Event Queue is passed in via the API.

In this example, the application will schedule a timer callback to execute in 1 second. The main thread that scheduled the timer will wait for the timer to execute, then clean up the application and exit

There is one program source file:

Program explanation: ScheduleTimers.java

Initializing the Context

Standard context creation code. Creating and scheduling timers only required an LBM context, no sources or receivers are needed.

00011          /*** Initialization: create necessary UM objects. ***/
00012          try {
00013              ctx = new LBMContext();
00014          }
00015          catch(LBMException ex)
00016          {
00017              System.err.println("Error initializing LBM objects: " + ex.toString());
00018              System.exit(1);
00019          }

Creating a Callback

The callback class defined below is the application callback that will be invoked when the scheduled timer expires. This callback will be executed on the UM context thread (at least for the purpose of this example it will be executed on the context thread.

00034      private static class callback implements LBMTimerCallback
00035      {
00036          public void onExpiration(java.lang.Object cbArg)
00037          {
00038              System.out.println("Timer executed. Set wait to 0 so application can cleanly exit");
00039              wait = 0;
00040          }
00041      }

Note that inside the callback, the global "wait" variable is set to 0, this allows the main thread to stop tight-looping and exit.

Scheduling the Timer Callback

Here the application is actually initializing and scheduling the callback timer, set to be executed in 1000 milliseconds. The return value should be saved by the application in the event that the application wishes to cancel the timer before it executes. Special care must be taken when cancelling timer callbacks, for more information please see

00021          callback cb = new callback();
00022          LBMTimer timer = new LBMTimer(ctx,1000,cb,null);

Wait for Timer

For the purpose of this example application, it is using the global variable "wait" as a semaphore essentially. Once the timer executes, wait will be set to 0 and the application can cleanly exit by deleting the context.

00024          while (wait == 1)
00025          {
00026              try {
00027                          Thread.sleep(500);
00028                      } catch (InterruptedException e) { }
00029          }