using timers to force an execution time

superpollo user at example.net
Thu Jul 16 06:34:20 EDT 2009


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?

$ python -V
Python 2.3.4
$ uname -a
Linux fisso 2.4.24 #1 Thu Feb 12 19:49:02 CET 2004 i686 GNU/Linux
$

bye



More information about the Python-list mailing list