Destroying Agents

using the same identifier will first be cancelled. If you want to cancel all jobs scheduled using the

"scheduleAction()" member function you should call the "cancelAllActions()" member function.

Destroying Agents

Ensuring that any outstanding job is cancelled, or deregistering interest in any event source, is impor- tant if you are endeavouring to destroy an agent object. If registrations are not cancelled, a circular ref- erence will exist between data held by the instance of the Agent base class and the derived object.

Such circular references defeat the Python reference counting mechanism, meaning that the object may never be destroyed.

To combat this particular situation, the member function "destroyReferences()" is included in the Agent base class. This will cancel all outstanding jobs and cancel any interest in other event sourc- es as well, destroying any circular references in the process. Provided there are no other references to the object elsewhere, Python should now be able to destroy it.

If you have circular references within your derived class, you may wish to extend this method in your own class so as to undo those circular references. Using the same member function name will make it less confusing to a user of your class as they will only have to call one function. If this is done, you should ensure however that the last thing the derived version of the method does is call the version of the method in the immediate base class.

Alarms and Timers

Alarms and timers are a means of having a callback function executed at some point of time in the fu- ture. The difference between an alarm and a timer is that an alarm is defined by an absolute value or point in time, where as a timer is defined by a relative offset in time. For an alarm this means supplying the clock time in seconds at which the callback should be executed. For a timer this means supplying the number of seconds from now at which point the callback should be executed.

class Object(netsvc.Agent): def __init__(self):

offset = 60

now = time.time() then = now + offset self.setAlarm(self.callback1,then) self.startTimer(self.callback2,offset,"timeout-1") self.startTimer(self.callback2,offset+10,"timeout-2")

def callback1(self): print "alarm"

def callback2(self,name): print name

if name == "timeout-1": self.cancelTimer("timeout-2")

29

Page 29
Image 29
Python 7.0pl5, Python Manual manual Destroying Agents, Alarms and Timers