repeat something in a thread, but stop when the program stops
Peter Otten
__peter__ at web.de
Mon Sep 27 10:30:41 EDT 2004
Harald Armin Massa wrote:
> I would like to have a way to stop that thread in a automatic way.
>
> one obvious solution would be:
>
> import time
> from threading import Thread
> import Queue
>
> class updater(Thread):
> stopper=Queue.Queue()
> def run(self):
> self.timegone=0
> while self.stopper.empty():
> time.sleep(0.5)
> self.timegone+=1
> if self.timegone>=600:
> print "you waited, time passed, I will do updates"
> do_updates()
> self.timegone=0
> print "updater stopped also"
As of 2.3 (I think) Queue.get() accepts a timeout parameter. You could
change the above to
from Queue import Queue, Empty
class updater(Thread):
stopper = Queue()
def run(self):
while True:
do_updates()
try:
self.stopper.get(True, 600)
except Empty:
pass
else:
break
and the sleeping thread should immediately wake up when it gets the stop
notification.
Peter
More information about the Python-list
mailing list