refactor: use psutil uptime and wmi lib for Windows temps; graceful SIGINT/SIGTERM/SIGBREAK shutdown

This commit is contained in:
snowy-yang committed 2026-09-12 20:18:26 +08:00
1 parent e39d1a0f52
commit 593b8011c6
4 files changed
+70 -20

No files matched your search

+30 -4
View File
@@ -2,6 +2,7 @@
import asyncio
import logging
import re
import signal
import sys
from pathlib import Path
@@ -260,15 +261,36 @@ class Bot:
watcher = asyncio.get_running_loop().create_task(self._watch_config(alerter))
log.info("机器人就绪,等待 OneBot 实现端连接...")
try:
await asyncio.Event().wait()
except (KeyboardInterrupt, asyncio.CancelledError):
pass
await self._wait_for_stop()
finally:
log.info("正在关闭...")
watcher.cancel()
await updater.stop()
await reporter.stop()
await alerter.stop()
await self.ob.stop()
log.info("已退出")
async def _wait_for_stop(self):
"""阻塞直到收到 Ctrl-C / SIGTERM。"""
stop = asyncio.Event()
loop = asyncio.get_running_loop()
def request_stop():
loop.call_soon_threadsafe(stop.set)
sigs = [signal.SIGINT, signal.SIGTERM]
if sys.platform == "win32" and hasattr(signal, "SIGBREAK"):
sigs.append(signal.SIGBREAK) # CTRL_BREAK / 任务管理器停止服务
for sig in sigs:
try:
loop.add_signal_handler(sig, request_stop)
except NotImplementedError: # Windows 回退
signal.signal(sig, lambda s, f: request_stop())
try:
await stop.wait()
except KeyboardInterrupt: # Windows 上 Ctrl-C 可能直接中断 await
pass
async def _watch_config(self, alerter: Alerter, interval: float = 5.0):
"""监测 config.toml 修改并热重载(端口/token 等需重启的项不生效)。"""
@@ -294,7 +316,11 @@ def main():
if sys.platform == "win32":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
cfg = load_config()
asyncio.run(Bot(cfg).run())
try:
asyncio.run(Bot(cfg).run())
except KeyboardInterrupt:
print("已退出")
sys.exit(0)
if __name__ == "__main__":