views:

92

answers:

2

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?

+2  A: 

wxwindows has its own timer. It supports one shot, and reoccurring events.

Andrew E. Falcon
Ah good call. Solves my wx problem, but not my overall python one.
bwawok
If the problem is you need to run it in a different thread, then there is nothing wrong with the loop around sleep(). If the task is short, I would try to avoid the thread so I wouldn't have to worry about locking resources.
Andrew E. Falcon
+2  A: 

A pattern more like this is probably what you should be doing, but it's hard to say because you didn't provide many details.

def do_background_work(self):
    # do work on a background thread, posting updates to the
    # GUI thread with CallAfter
    while True:
        # do stuff
        wx.CallAfter(self.update_progress, percent_complete)

def update_progress(self, percent_complete):
    # update the progress bar from the GUI thread
    self.gauge.SetValue(percent_complete)

def on_start_button(self, event):
    # start doing background work when the user hits a button
    thread = threading.Thread(target=self.do_background_work)
    thread.setDaemon(True)
    thread.start()
FogleBird