< Day Day Up > |
The Context object has considerably more functionality than just life cycle support. One of the more useful areas is event scheduling ”the ability to specify when a callback should occur. As you saw in Chapter 6, "Introduction to WebLogic Workshop Controls and Components," controls can implement callbacks (basically, methods on the caller) that a control can call at special times, such as when a long-running process has completed. Occasionally, it's useful to simply define a callback method and then schedule it to be called at a later clock time. A simple timer is the most obvious use of this feature, but any regularly scheduled event can be managed. The Context object can be used to schedule callbacks without the need for a timer. To support event processing, you must provide a callback method and then use an instance of a ControlContext object to schedule when the event should be delivered. Assume you have an alarm callback that returns a message as well as the time it was sent: public interface Callback { void onAlarmRinging(String message, long time); } You can schedule the callback by using the scheduleEvent method of the Context object. This method takes four arguments:
The setAlarm method, shown in Listing 8.1, is a complete example of preparing the scheduled callback to send the onAlarmRinging callback when the alarm time is reached. The shaded code shows an example of setting an event to call onAlarmRinging when the specified time is reached. Listing 8.1. The setAlarm Method /** * * @common:operation */ public void setAlarm(String msg,long delayInMsecs) { long alarmTime = new Date().getTime() + delayInMsecs; Object[] callbackArgs = new Object[2]; callbackArgs[0] = new String(msg); callbackArgs[1] = new Long(alarmTime); context.scheduleEvent("onAlarmRinging", callbackArgs, alarmTime, true); } The converse of scheduling an event is canceling it. The ControlContext interface provides a cancelEvents method, which takes as a single argument the name of the callback event to cancel. Listing 8.2 shows how you could cancel the onAlarmRinging event. Listing 8.2. Canceling a Previously Scheduled Event/** * @common:operation */ public void cancelAlarm() { context.cancelEvents("onAlarmRinging"); } Scheduling and canceling events are excellent ways to perform set and forget processing. However, on occasion you need to send an event immediately. The ControlContext interface provides a method for just such an occurrence: sendEvent . sendEvent looks much like scheduleEvent , except that it takes only two arguments ”the name of the event and the event's object array argument set. As shown in the following shaded code, you could force an onAlarmRinging callback to fire immediately: Object[] callbackArgs = new Object[2]; callbackArgs[0] = new String(msg); callbackArgs[1] = new Long(alarmTime); context.sendEvent("onAlarmRinging", callbackArgs);
|
< Day Day Up > |