Managing timing in Python calls

cmdrrickhunter@yaho.com conrad.ammon at gmail.com
Mon Dec 15 21:45:41 CET 2008


I believe WxTimerEvent is handled using the event queue, which isn't
going to do what you want.  An event which goes through the queue does
not get processed until you return to the queue.

What you want to do is actually a rather difficult task to do
generically.  Should the task be interrupted immediately?  Or is a
tiny latency acceptable?  Should the function being terminated get to
handle its own termination?  Or should the termination be forced on
it.  What sort of overhead is acceptable for this "set_timeout"
behavior?

I would not be surprised if there isn't a built in solution, because
its so hard, but rather built in tools which can be used to do it.

If your timeouts are on the order of seconds, you might be able to
just check time.time() at the begining, and compare it to the current
time later in the function.  This could be on the main thread or on a
worker thread.

If you need better handling, you may want to look at how condition
variables and such work.

Finally, thread has a function to send a Keyboard Interrupt to the
main thread.  I believe you could do your work on the main thread, and
catch the interrupt.

"Background" tasks are not easy to implement in any language (other
than perhaps AJAX ;-) ).

Remember, Python does not support truly simultaneous threads.  It
actually does timeslices of about 100 operations.  Any solution you
choose should work given this information.

And as for a "nicer" construct, I personally just learned of how to
handle the "with" command.  I could see something like

class Timeout:
    def __init__(self, t):
        self.t = t
    def __enter__(self):
        self.start = time.time()
    def __exit__(self, x, y, z):
        return None
    def __nonzero__(self):
        return time.time() - self.start <= self.t


def doSomethingLong(timeout = True): # true guarentees bailout never
occurs
   while timeout:
       doAnIteration()

with Timeout(3) as t:
    doSomethingLong(t)



and have your Timeout class have a flag which it sets when
doSomethingLong needs to bail out, using whatever method is "best" for
your particular application.  This is, of course pseudocode - I've not
run it through python msyself.  Hopefully any errors are obvious
enough that you can work around them.



More information about the Python-list mailing list