Skip to content

Instantly share code, notes, and snippets.

@ceoro9
Created February 4, 2018 21:03
Show Gist options
  • Save ceoro9/fe781c2bb0fac140c0c8941aad8ecabf to your computer and use it in GitHub Desktop.
Save ceoro9/fe781c2bb0fac140c0c8941aad8ecabf to your computer and use it in GitHub Desktop.
#!/usr/bin/python3.6
import redis
import threading
class Listener(threading.Thread):
def __init__(self, r, channels):
super(Listener, self).__init__()
self.redis = r
self.pubsub = self.redis.pubsub()
self.pubsub.subscribe(channels)
def work(self, item):
print(item['channel'], ":", item['data'])
def run(self):
for item in self.pubsub.listen():
if item['data'] == "KILL":
self.pubsub.unsubscribe()
print(self, "unsubscribed and finished")
break
else:
self.work(item)
if __name__ == "__main__":
r = redis.Redis()
client = Listener(redis.Redis(), ['test'])
client.start()
r.publish('test', 'this will reach the listener')
r.publish('fail', 'this will not')
r.publish('test', 'KILL')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment