diff weatherlog/daemon.py @ 19:7117db65715e

Make weatherlog shutdown properly by handling SIGTERM.
author Paul Fisher <paul@pfish.zone>
date Mon, 20 Jan 2020 23:36:23 -0500
parents 39c0686e6765
children 92367b644e29
line wrap: on
line diff
--- a/weatherlog/daemon.py	Thu Jan 16 23:52:30 2020 -0500
+++ b/weatherlog/daemon.py	Mon Jan 20 23:36:23 2020 -0500
@@ -2,6 +2,8 @@
 
 import argparse
 import enum
+import signal
+import threading
 import time
 import typing as t
 
@@ -21,18 +23,21 @@
     log: logger.BufferedLogger,
     writer: logger.RemoteWriter,
     interval: int = DEFAULT_INTERVAL_SECS,
-):
+) -> None:
     """Sets up and runs a logger daemon."""
-    log.start()
+    evt = threading.Event()
+    signal.signal(signal.SIGTERM, lambda *args: evt.set())
     cycle = 0
     start = time.time()
+    running = True
+    log.start()
     try:
-        while True:
+        while running:
             log.write(rd.read().as_dict())
             cycle += 1
             target = start + interval * cycle
             now = time.time()
-            time.sleep(max(target - now, MIN_INTERVAL_SECS))
+            running = not evt.wait(max(target - now, MIN_INTERVAL_SECS))
     finally:
         log.close()
 
@@ -54,7 +59,7 @@
     auth: t.Dict[str, object]
 
 
-def parse_config(config_file: str):
+def parse_config(config_file: str) -> _Config:
     with open(config_file, 'r') as infile:
         config = toml.load(infile)
     return _Config(