feat 多线程处理事件

This commit is contained in:
jxxghp 2023-10-17 19:04:42 +08:00
parent e57b6adba1
commit 453ef94e4d
3 changed files with 47 additions and 3 deletions

View File

@ -13,6 +13,7 @@ from app.core.event import Event as ManagerEvent
from app.core.event import eventmanager, EventManager
from app.core.plugin import PluginManager
from app.db import SessionFactory
from app.helper.thread import ThreadHelper
from app.log import logger
from app.scheduler import Scheduler
from app.schemas import Notification
@ -51,6 +52,8 @@ class Command(metaclass=Singleton):
self.chain = CommandChian(self._db)
# 定时服务管理
self.scheduler = Scheduler()
# 线程管理器
self.threader = ThreadHelper()
# 内置命令
self._commands = {
"/cookiecloud": {
@ -192,7 +195,11 @@ class Command(metaclass=Singleton):
[class_name, method_name] = names
if class_name in self.pluginmanager.get_plugin_ids():
# 插件事件
self.pluginmanager.run_plugin_method(class_name, method_name, event)
self.threader.submit(
self.pluginmanager.run_plugin_method,
class_name, method_name, event
)
else:
# 检查全局变量中是否存在
if class_name not in globals():
@ -206,7 +213,10 @@ class Command(metaclass=Singleton):
class_obj = globals()[class_name]()
# 检查类是否存在并调用方法
if hasattr(class_obj, method_name):
getattr(class_obj, method_name)(event)
self.threader.submit(
getattr(class_obj, method_name),
event
)
except Exception as e:
logger.error(f"事件处理出错:{str(e)} - {traceback.format_exc()}")

31
app/helper/thread.py Normal file
View File

@ -0,0 +1,31 @@
from concurrent.futures import ThreadPoolExecutor
from app.utils.singleton import Singleton
class ThreadHelper(metaclass=Singleton):
"""
线程池管理
"""
def __init__(self, max_workers=50):
self.pool = ThreadPoolExecutor(max_workers=max_workers)
def submit(self, func, *args, **kwargs):
"""
提交任务
:param func: 函数
:param args: 参数
:param kwargs: 参数
:return: future
"""
return self.pool.submit(func, *args, **kwargs)
def shutdown(self):
"""
关闭线程池
:return:
"""
self.pool.shutdown()
def __del__(self):
self.shutdown()

View File

@ -16,14 +16,15 @@ if SystemUtils.is_frozen():
sys.stdout = open(os.devnull, 'w')
sys.stderr = open(os.devnull, 'w')
from app.command import Command
from app.core.config import settings
from app.core.module import ModuleManager
from app.core.plugin import PluginManager
from app.db.init import init_db, update_db
from app.helper.thread import ThreadHelper
from app.helper.display import DisplayHelper
from app.helper.sites import SitesHelper
from app.scheduler import Scheduler
from app.command import Command
# App
App = FastAPI(title=settings.PROJECT_NAME,
@ -146,6 +147,8 @@ def shutdown_server():
DisplayHelper().stop()
# 停止定时服务
Scheduler().stop()
# 停止线程池
ThreadHelper().shutdown()
# 停止前端服务
stop_frontend()