The TaskThread class allows you to create threads that execute a specific action at a specified interval, by subclassing - just override the task() method. You can also shutdown a TaskThread without having to wait for it to finish "sleeping" (due to the use of threading.Event objects as an alternative to time.sleep()).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | import threading
class TaskThread(threading.Thread):
"""Thread that executes a task every N seconds"""
def __init__(self):
threading.Thread.__init__(self)
self._finished = threading.Event()
self._interval = 15.0
def setInterval(self, interval):
"""Set the number of seconds we sleep between executing our task"""
self._interval = interval
def shutdown(self):
"""Stop this thread"""
self._finished.set()
def run(self):
while 1:
if self._finished.isSet(): return
self.task()
# sleep for interval or until shutdown
self._finished.wait(self._interval)
def task(self):
"""The task done by this thread - override in subclasses"""
pass
|
In a lot of cases we want a thread to do something every few seconds, for example an email program may want to check if there is new mail on the POP3 server. Using TaskThread we can create classes for specific tasks - this is a great way to work with threads in general.
I know that wxPython has a wxTimer class that does the same thing, presumably using wxWindows event loop instead of threads, and there may be other ways of doing this as well.
raise an exception to ensure subclass overrides task(). If no exception is raised by the base class task() method, it might just quietly 'pass' in the backgroud, and the error would be hard to detect.
Instead of: def task(): pass
using: def task(): raise Exception #( or a more specific exception )
..would prevent errors arising from attempting to use the TaskThread class without subclassing it, and properly overriding the task() method.
Improvement. You might also try this:
It allows you to specify a function to be executed with specified params every n seconds.
This seems odd ... I tried to use this functionality as follows :
this results in the following output under Win NT.
So the calling program doesn't get control again. I thougt that it is the point of threads to allow just that. Wondering ...
re: This seems odd ... Change the tt.run() to tt.start()
Doing it in wxPython.
</pre>