sleep and Timer

Bengt Richter bokr at oz.net
Thu May 29 01:49:33 EDT 2003


On Wed, 28 May 2003 23:34:18 +0800, "Rob Hall" <robhall at ii.net> wrote:

>I have a thread which needs to download a web page and process it
>periodically (every couple of minutes).  Up until now, in the thread I have
>had something like this:
>
>def run(self):
>    while self.quit = false:
>        DO SOME STUFF
>        time.sleep(120)
What if instead of sleeping you had an event object and waited for it with a timeout of 120, e.g.,
         evt.wait(120)
         if evt.isSet(): # means another thread set the event, meaning kill
             # die here -- should be immediately after event is set
         #otherwise just let loop continue around
>

E.g., (Warning! Not tested beyond what you see below):

====< periodic.py >=================================
import threading, time
evt = threading.Event()

def periodic(dt, reps):
    for i in xrange(reps):
        print i, time.clock()-t0
        evt.wait(dt)
        if evt.isSet():
            print 'dead', time.clock()-t0
            break
    
pt = threading.Thread(target=periodic, args=(5, 20))
t0 = time.clock()
pt.start()
time.sleep(16)
print 'killing time =,', time.clock()-t0
evt.set()
====================================================
[22:44] C:\pywk\clp>periodic.py
0 0.00135519979349
1 5.00633264665
2 10.0135268551
3 15.0207151968
killing time =, 16.0019351616
dead 16.0219212157

Note that the cutoff didn't wait for the next full 5 seconds to elapse.
Note also that I haven't tried this exact thing before, so there may be a pitfall.

HTH

Regards,
Bengt Richter




More information about the Python-list mailing list