Correct way to do timer function in Python

Posted by bwawok on Stack Overflow See other posts from Stack Overflow or by bwawok
Published on 2010-05-25T16:28:36Z Indexed on 2010/05/25 16:31 UTC
Read the original article Hit count: 267

Filed under:
|
|

Hi. I have a GUI application that needs to do something simple in the background (update a wx python progress bar, but that doesn't really matter). I see that there is a threading.timer class.. but there seems to be no way to make it repeat. So if I use the timer, I end up having to make a new thread on every single execution... like :

import threading
import time

def DoTheDew():
    print "I did it"
    t = threading.Timer(1, function=DoTheDew)
    t.daemon = True
    t.start()    

if __name__ == '__main__':
    t = threading.Timer(1, function=DoTheDew)
    t.daemon = True
    t.start()
    time.sleep(10)

This seems like I am making a bunch of threads that do 1 silly thing and die.. why not write it as :

import threading
import time

def DoTheDew():
    while True:
        print "I did it"
        time.sleep(1)


if __name__ == '__main__':
    t = threading.Thread(target=DoTheDew)
    t.daemon = True
    t.start()
    time.sleep(10)

Am I missing some way to make a timer keep doing something? Either of these options seems silly... I am looking for a timer more like a java.util.Timer that can schedule the thread to happen every second... If there isn't a way in Python, which of my above methods is better and why?

© Stack Overflow or respective owner

Related posts about python

Related posts about threading