Reputation: 1319
import redis
import threading
class Listener(threading.Thread):
def __init__(self, r, channel):
threading.Thread.__init__(self)
self.redis = r
self.pubsub = self.redis.pubsub()
self.pubsub.subscribe(channel)
def run(self):
for item in self.pubsub.listen():
# do stuff
pass
in the above code how I do stop the thread?
Below I have an example code to show you what I would like:
class Listener(threading.Thread):
def __init__(self, r, channel):
threading.Thread.__init__(self)
self.redis = r
self.pubsub = self.redis.pubsub()
self.pubsub.subscribe(channel)
self.stop = False
def run(self):
while not stop:
# get item from channel
So when the attribute stop == True the thread will exit the loop and will finish. Is that possible? If it is not what are the alternatives?
Upvotes: 2
Views: 4203
Reputation: 4879
There is a useful gist that shows how to pass in a command that will break the loop and unsubscribe. This may be useful to see how you could do it in other ways.
for item in self.pubsub.listen():
if item['data'] == "KILL":
self.pubsub.unsubscribe()
print self, "unsubscribed and finished"
break
else:
self.work(item)
You can see the example code here:
Upvotes: 4