Python 7.0pl5 Benutzerhandbuch

Seite von 124
Event Framework
34
should call this member function. This member function can also be called when an external signal
intended to shutdown the program is received. Doing this in the latter case means you don’t need to
have separate code for the two different cases.
If an agent is interested in the fact that the program is being shutdown, it can call the "
subscribe-
Shutdown()
" member function, supplying a callback function to be called when such an event does
occur. Note that the call to "
scheduleShutdown()
" will result in the dispatcher being stopped au-
tomatically, so you do not need to do it explicitly. If necessary, an agent can unsubscribe from program
shutdown notifications by calling the member function "
unsubscribeShutdown()
".
class Agent(netsvc.Agent):
def __init__(self):
self.subscribeShutdown(self.shutdown)
self.subscribeSignal(self.signal,signal.SIGINT)
self.subscribeSignal(self.signal,signal.SIGTERM)
self.startTimer(self.timeout,60)
def timeout(self):
self.scheduleShutdown()
def signal(self,signum):
self.scheduleShutdown()
def shutdown(self,category):
if category == netsvc.SHUTDOWN_PENDING:
# shutdown is pending
else:
# shutdown has arrived
When shutdown is initiated, any callback function supplied by an agent will actually be called twice.
The first time it is called, it will be called with the value "
SHUTDOWN_PENDING
". Once all subscribed
agents have been notified that shutdown is pending, the callback function will then be subsequently
called again, this time with the value "
SHUTDOWN_ARRIVED
". Upon all agents receiving the second
notification, the dispatcher will be stopped and the process will exit.
Note that the second of these notifications will not occur immediately after the first. Exactly how much
time may pass is dependent on a number of factors. The first determining factor is the argument sup-
plied to the "
scheduleShutdown()
" member function. If no argument is supplied, or a value of
"
0
" is supplied, there will be an inbuilt delay of 1 second between shutdown being scheduled and the
program actually being shutdown.
This implicit delay gives scope for activities which can’t be factored into a single callback function
time to be carried out. For example, it may be necessary to send data via a socket to some remote host
and wait for the response. If the default value of 1 second is insufficient, or is too long a time, it can
be overridden in a number of ways.
The first way of overriding the default value of 1 second is by setting the environment variable
OTCLIB_SHUTDOWNDELAY
. If this is done, it should be set to a value representing the number of
milliseconds to wait. An alternative is to modify each call of "
scheduleShutdown()
" and explic-