调试定时装饰器,优化代码

This commit is contained in:
liuwei
2025-03-20 15:17:33 +08:00
parent 20b8ba0252
commit aec1ccb0b8

View File

@@ -2,6 +2,7 @@ import functools
import inspect
import logging
import weakref
import sys
from typing import Callable, Optional, Dict, List, Any
LOG = logging.getLogger("JobDecorator")
@@ -26,6 +27,7 @@ class TaskRegistry:
def register_task(self, task_info):
"""注册任务信息"""
self.tasks.append(task_info)
LOG.info(f"已注册任务: {task_info['name']}, cron: {task_info['cron']}")
def register_instance(self, instance):
"""注册实例到实例列表"""
@@ -36,6 +38,7 @@ class TaskRegistry:
# 添加实例的弱引用
self.instances.append(weakref.ref(instance))
LOG.info(f"已注册实例: {instance.__class__.__name__}")
# 清理已失效的弱引用
self.instances = [ref for ref in self.instances if ref() is not None]
@@ -70,10 +73,45 @@ class TaskRegistry:
LOG.info(f"{class_name} 添加定时任务: {task['method_name']}, 时间: {time_str}")
instance.onEveryTime(time_str, method)
def scan_for_instances(self):
"""扫描已加载的模块,查找所有已创建的类实例"""
LOG.info("扫描已加载的模块,查找类实例...")
# 获取所有已加载的模块
for module_name, module in sys.modules.items():
# 跳过内置模块和标准库模块
if module_name.startswith('_') or not hasattr(module, '__file__') or module.__file__ is None:
continue
# 查找模块中的所有全局变量
for var_name in dir(module):
try:
var = getattr(module, var_name)
# 检查是否是类实例
if isinstance(var, object) and not isinstance(var, type) and hasattr(var, '__class__'):
# 检查类是否有被装饰的方法
class_name = var.__class__.__name__
has_decorated_method = False
for task in self.tasks:
if task["class_name"] == class_name and hasattr(var, task["method_name"]):
has_decorated_method = True
break
if has_decorated_method:
LOG.info(f"在模块 {module_name} 中找到实例: {class_name}")
self.register_instance(var)
except Exception as e:
# 忽略获取属性时的错误
pass
def initialize(self):
"""初始化任务系统,扫描所有已创建的实例并注册任务"""
LOG.info("初始化任务系统")
# 扫描已加载的模块,查找所有已创建的类实例
self.scan_for_instances()
# 清理已失效的弱引用
self.instances = [ref for ref in self.instances if ref() is not None]
@@ -82,6 +120,11 @@ class TaskRegistry:
instance = ref()
if instance:
self.register_tasks_for_instance(instance)
# 输出已注册的任务信息
LOG.info(f"已注册 {len(self.tasks)} 个任务")
for task in self.tasks:
LOG.info(f"任务: {task['name']}, 方法: {task['method_name']}, cron: {task['cron']}")
# 获取任务注册表实例
@@ -111,8 +154,6 @@ def scheduled_job(cron: str, name: Optional[str] = None, enabled: bool = True):
}
registry.register_task(task_info)
LOG.info(f"注册定时任务: {task_name}, cron: {cron}, enabled: {enabled}")
@functools.wraps(func)
def wrapper(*args, **kwargs):
# 如果是实例方法的第一次调用,注册实例