feat: quit gracefully redis
This commit is contained in:
10
worker.py
10
worker.py
@@ -1,4 +1,5 @@
|
|||||||
import sched
|
import sched
|
||||||
|
import time
|
||||||
from threading import Thread
|
from threading import Thread
|
||||||
import json
|
import json
|
||||||
|
|
||||||
@@ -14,12 +15,16 @@ INTERVAL_IMAGE = 0.05 # 20/s
|
|||||||
class EventListener(Thread):
|
class EventListener(Thread):
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
super(EventListener, self).__init__()
|
super(EventListener, self).__init__()
|
||||||
|
self.keep_running = True
|
||||||
self.dbcon = Redis()
|
self.dbcon = Redis()
|
||||||
self.pubsub = self.dbcon.pubsub()
|
self.pubsub = self.dbcon.pubsub()
|
||||||
self.pubsub.subscribe(['move', 'look'])
|
self.pubsub.subscribe(['move', 'look'])
|
||||||
|
|
||||||
def run(self) -> None:
|
def run(self) -> None:
|
||||||
for item in self.pubsub.listen():
|
while self.keep_running:
|
||||||
|
item = self.pubsub.get_message()
|
||||||
|
if not item:
|
||||||
|
time.sleep(0.01)
|
||||||
channel = item['channel'].decode()
|
channel = item['channel'].decode()
|
||||||
data = item['data']
|
data = item['data']
|
||||||
if not isinstance(data, bytes):
|
if not isinstance(data, bytes):
|
||||||
@@ -29,9 +34,10 @@ class EventListener(Thread):
|
|||||||
self.handle_message(channel, data)
|
self.handle_message(channel, data)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
pass # todo
|
pass # todo
|
||||||
|
self.pubsub.close()
|
||||||
|
|
||||||
def stop(self):
|
def stop(self):
|
||||||
self.pubsub.close()
|
self.keep_running = False
|
||||||
|
|
||||||
def handle_message(self, channel: str, data: bytes):
|
def handle_message(self, channel: str, data: bytes):
|
||||||
data_dict = json.loads(data.decode())
|
data_dict = json.loads(data.decode())
|
||||||
|
|||||||
Reference in New Issue
Block a user