Python 7.0pl5 Benutzerhandbuch

Seite von 124
Event Framework
26
jobs will be reclassified as standard jobs and subsequently executed. When scheduling a job, if jobs of
the same type already exist, the new job will be placed at the end of the list of jobs of the same type.
To schedule a job the dispatcher member function "
schedule()
" must be called, supplying the call-
back function and the type of job. To set the dispatcher running, the member function "
run()
" is
called. If the only feature of the event system which is used is that of scheduling jobs, the "
run()
"
function will return when there are no more jobs to execute. A job may prematurely stop the dispatcher
by calling the "
stop()
" member function. If a callback raises an exception which is not caught and
processed within the callback itself, the details of the exception will be logged, the dispatcher stopped
and Python exited immediately.
def callback(message="hi"):
print message
dispatcher = netsvc.Dispatcher()
dispatcher.schedule(callback,netsvc.IDLE_JOB)
dispatcher.schedule(callback,netsvc.STANDARD_JOB)
dispatcher.schedule(callback,netsvc.PRIORITY_JOB)
dispatcher.run()
The callback supplied when scheduling a job can be a normal function or a member function associated
with an instance of a class. If a callback function is scheduled directly with the dispatcher in this way,
it will be called with no arguments and cannot be cancelled once scheduled.
If it is necessary to pass arguments to a callback function, an instance of the
Job
class must be used
in place of the actual callback function. The
Job
class will hold a reference to the real callback func-
tion as well as the arguments. When the job is executed it will call the callback function with the sup-
plied arguments.
job = netsvc.Job(callback,("bye",))
dispatcher.schedule(job,netsvc.IDLE_JOB)
In addition to providing a means of supplying arguments to a callback function, the
Job
class provides
a means of cancelling execution of a callback function. In order to do this, a reference to the instance
of the
Job
class should be kept. If it is subsequently necessary to cancel execution of the callback prior
to it having being called, the "
cancel()
" member function of the
Job
class should be called.
job = None
def callback1():
print "hi"
job.cancel()
def callback2():
print "hi"
dispatcher.schedule(callback1,netsvc.PRIORITY_JOB)
job = netsvc.Job(callback2)
dispatcher.schedule(job,netsvc.STANDARD_JOB)