mirror of
https://github.com/LiteyukiStudio/LiteyukiBot.git
synced 2025-07-28 09:11:20 +00:00
🐛 修复生命周期钩子函数的问题
This commit is contained in:
@ -8,12 +8,17 @@ Copyright (C) 2020-2024 LiteyukiStudio. All Rights Reserved
|
||||
@File : manager.py
|
||||
@Software: PyCharm
|
||||
"""
|
||||
import asyncio
|
||||
import threading
|
||||
from multiprocessing import Process
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from liteyuki.comm import Channel
|
||||
from liteyuki.log import logger
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from liteyuki.bot import LiteyukiBot
|
||||
|
||||
TIMEOUT = 10
|
||||
|
||||
__all__ = [
|
||||
@ -26,14 +31,15 @@ class ProcessManager:
|
||||
在主进程中被调用
|
||||
"""
|
||||
|
||||
def __init__(self, bot, chan: Channel):
|
||||
def __init__(self, bot: "LiteyukiBot", chan: Channel):
|
||||
self.bot = bot
|
||||
self.chan = chan
|
||||
self.processes: dict[str, tuple[callable, tuple, dict]] = {}
|
||||
self.targets: dict[str, tuple[callable, tuple, dict]] = {}
|
||||
self.processes: dict[str, Process] = {}
|
||||
|
||||
def start(self, name: str, delay: int = 0):
|
||||
"""
|
||||
开启后自动监控进程
|
||||
开启后自动监控进程,并添加到进程字典中
|
||||
Args:
|
||||
name:
|
||||
delay:
|
||||
@ -42,33 +48,30 @@ class ProcessManager:
|
||||
|
||||
"""
|
||||
|
||||
if name not in self.processes:
|
||||
if name not in self.targets:
|
||||
raise KeyError(f"Process {name} not found.")
|
||||
|
||||
def _start():
|
||||
should_exit = False
|
||||
while not should_exit:
|
||||
process = Process(target=self.processes[name][0], args=(self.chan, *self.processes[name][1]), kwargs=self.processes[name][2])
|
||||
process = Process(target=self.targets[name][0], args=(self.chan, *self.targets[name][1]), kwargs=self.targets[name][2])
|
||||
self.processes[name] = process
|
||||
process.start()
|
||||
while not should_exit:
|
||||
# 0退出 1重启
|
||||
data = self.chan.receive(name)
|
||||
print("Received data: ", data, name)
|
||||
if data == 1:
|
||||
logger.info("Restarting LiteyukiBot...")
|
||||
process.terminate()
|
||||
process.join(TIMEOUT)
|
||||
if process.is_alive():
|
||||
process.kill()
|
||||
logger.info(f"Restarting process {name}")
|
||||
asyncio.run(self.bot.lifespan.before_shutdown())
|
||||
asyncio.run(self.bot.lifespan.before_restart())
|
||||
self.terminate(name)
|
||||
break
|
||||
|
||||
elif data == 0:
|
||||
logger.info("Stopping LiteyukiBot...")
|
||||
logger.info(f"Stopping process {name}")
|
||||
asyncio.run(self.bot.lifespan.before_shutdown())
|
||||
should_exit = True
|
||||
process.terminate()
|
||||
process.join(TIMEOUT)
|
||||
if process.is_alive():
|
||||
process.kill()
|
||||
self.terminate(name)
|
||||
else:
|
||||
logger.warning("Unknown data received, ignored.")
|
||||
|
||||
@ -78,16 +81,25 @@ class ProcessManager:
|
||||
threading.Thread(target=_start).start()
|
||||
|
||||
def add_target(self, name: str, target, *args, **kwargs):
|
||||
self.processes[name] = (target, args, kwargs)
|
||||
self.targets[name] = (target, args, kwargs)
|
||||
|
||||
def join(self):
|
||||
for name, process in self.processes:
|
||||
for name, process in self.targets:
|
||||
process.join()
|
||||
|
||||
def terminate(self):
|
||||
for name, process in self.processes:
|
||||
process.terminate()
|
||||
process.join(TIMEOUT)
|
||||
if process.is_alive():
|
||||
process.kill()
|
||||
self.processes = []
|
||||
def terminate(self, name: str):
|
||||
"""
|
||||
终止进程并从进程字典中删除
|
||||
Args:
|
||||
name:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
if name not in self.targets:
|
||||
raise logger.warning(f"Process {name} not found.")
|
||||
process = self.processes[name]
|
||||
process.terminate()
|
||||
process.join(TIMEOUT)
|
||||
if process.is_alive():
|
||||
process.kill()
|
||||
|
@ -1,16 +1,16 @@
|
||||
import threading
|
||||
from multiprocessing import Event, Queue
|
||||
from typing import Optional
|
||||
from typing import Optional, TYPE_CHECKING
|
||||
|
||||
import nonebot
|
||||
|
||||
import liteyuki
|
||||
from liteyuki.core.nb import adapter_manager, driver_manager
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from liteyuki.comm.channel import Channel
|
||||
|
||||
timeout_limit: int = 20
|
||||
|
||||
"""导出对象,用于进程通信"""
|
||||
chan_in_spawn: Optional["liteyuki.Channel"] = None
|
||||
"""导出对象,用于主进程与nonebot通信"""
|
||||
chan_in_spawn_nb: Optional["Channel"] = None
|
||||
|
||||
|
||||
def nb_run(chan, *args, **kwargs):
|
||||
@ -18,14 +18,15 @@ def nb_run(chan, *args, **kwargs):
|
||||
初始化NoneBot并运行在子进程
|
||||
Args:
|
||||
|
||||
chan:
|
||||
*args:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
global chan_in_spawn
|
||||
chan_in_spawn = chan
|
||||
global chan_in_spawn_nb
|
||||
chan_in_spawn_nb = chan
|
||||
nonebot.init(**kwargs)
|
||||
driver_manager.init(config=kwargs)
|
||||
adapter_manager.init(kwargs)
|
||||
|
Reference in New Issue
Block a user