using timers to force an execution time

Diez B. Roggisch deets at nospam.web.de
Thu Jul 16 07:03:55 EDT 2009


superpollo wrote:

> 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?

Of course the inner loop isn't affected by the set event - how should it be,
if you don't check it.

if you rewrite it as this:

while True:
    for repeat in range(10):
        if e.isSet():
           break
        print time.time()
        time.sleep(.66)

it should terminate earlier.

What you can't achieve in python without major black magic hackery that is
very dangerous is to terminate a thread while it is executing. Termination
has to be co-operative.

Diez



More information about the Python-list mailing list