using timers to force an execution time

Paul Moore p.f.moore at gmail.com
Thu Jul 16 09:46:13 EDT 2009


2009/7/16 superpollo <user at example.net>:
> hello.
>
> based upon previuos suggestions, i tried to write a program in which i would
> like to have a certain code fragment to execute only for a specified amount
> of time (say 3 seconds), then bail out.
>
> but i get the following:
>
> $ cat tmr004.py
> #!/usr/bin/python -u
>
> import threading , time
>
> e = threading.Event()
> t = threading.Timer(3.0, e.set)
> t.start()
> print time.asctime(time.localtime(time.time()))
> while not e.isSet():
>    for repeat in range(10):
>        print time.time()
>        time.sleep(0.66)
> print time.asctime(time.localtime(time.time()))
> $ ./tmr004.py
> Thu Jul 16 12:31:27 2009
> 1247740287.44
> 1247740288.1
> 1247740288.76
> 1247740289.42
> 1247740290.08
> 1247740290.74
> 1247740291.4
> 1247740292.06
> 1247740292.72
> 1247740293.38
> Thu Jul 16 12:31:34 2009
> $
>
> see? the while body ran for about 7 seconds... i bet it has to do with the
> fact that the timer does not control inner loops... any suggestion?

Clearly, this isn't what you are actually trying to do. For this case,
your event is getting set when you expect, but your main thread does
not check the event often enough to let it stop in a timely manner.

To fix this, remove the inner "for repeat in range(10)" loop. But I
assume that your "real" code isn't something that you can fix this
easily. If you describe your real requirement, it may be possible to
give you a better answer. (But that answer will almost certainly not
be a way of interrupting one thread from another - that's not really
possible with Python - but rather a way of achieving your goal without
*needing* to interrupt one thread from another).

Paul.

PS If you really must interrupt one thread from another, you can use C
code (or ctypes) to call the PyThreadState_SetAsyncExc API. But I'm
not going to tell you how, as it's almost certainly *not* what you
want to do in practice :-)



More information about the Python-list mailing list