sleep and Timer

Peter Hansen peter at engcorp.com
Wed May 28 14:18:01 EDT 2003


Rob Hall 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)

Perhaps simpler than your Timer based approach would be something like this:

def run(self):
    import time
    start = time.time()
    while not self.quit:  # bad practice to test equal to false
        if time.time() - start >= 120:
            DO SOME STUFF
            start = time.time()
        else:
            time.sleep(5)

This way the thread wakes up every few seconds to check whether it should
terminate.  For small scripts, this might be good enough.

-Peter




More information about the Python-list mailing list