Compare commits

...

2 Commits

Author SHA1 Message Date
Cp0204
846bf0345a 🔧 增强代码可读性与优化日志
Some checks failed
Docker Publish / build-and-push (push) Has been cancelled
2025-10-14 14:12:30 +08:00
ypq123456789
95ddc95c79
🐛 补充修复:添加 APScheduler 调度器参数,彻底解决任务堆积问题 (#126) 2025-10-14 13:31:02 +08:00
2 changed files with 39 additions and 10 deletions

View File

@ -33,6 +33,19 @@ parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
sys.path.insert(0, parent_dir) sys.path.insert(0, parent_dir)
from quark_auto_save import Quark, Config, MagicRename from quark_auto_save import Quark, Config, MagicRename
print(
r"""
____ ___ _____
/ __ \ / | / ___/
/ / / / / /| | \__ \
/ /_/ / / ___ |___/ /
\___\_\/_/ |_/____/
-- Quark-Auto-Save --
"""
)
sys.stdout.flush()
def get_app_ver(): def get_app_ver():
"""获取应用版本""" """获取应用版本"""
@ -60,6 +73,7 @@ PLUGIN_FLAGS = os.environ.get("PLUGIN_FLAGS", "")
DEBUG = os.environ.get("DEBUG", "false").lower() == "true" DEBUG = os.environ.get("DEBUG", "false").lower() == "true"
HOST = os.environ.get("HOST", "0.0.0.0") HOST = os.environ.get("HOST", "0.0.0.0")
PORT = os.environ.get("PORT", 5005) PORT = os.environ.get("PORT", 5005)
TASK_TIMEOUT = int(os.environ.get("TASK_TIMEOUT", 1800))
config_data = {} config_data = {}
task_plugins_config_default = {} task_plugins_config_default = {}
@ -83,6 +97,8 @@ logging.basicConfig(
# 过滤werkzeug日志输出 # 过滤werkzeug日志输出
if not DEBUG: if not DEBUG:
logging.getLogger("werkzeug").setLevel(logging.ERROR) logging.getLogger("werkzeug").setLevel(logging.ERROR)
logging.getLogger("apscheduler").setLevel(logging.ERROR)
sys.modules["flask.cli"].show_server_banner = lambda *x: None
def gen_md5(string): def gen_md5(string):
@ -472,34 +488,42 @@ def add_task():
def run_python(args): def run_python(args):
logging.info(f">>> 定时运行任务") logging.info(f">>> 定时运行任务")
try: try:
# 使用 subprocess 替代 os.system并设置超时时间默认30分钟
timeout = int(os.environ.get("TASK_TIMEOUT", "1800")) # 秒
result = subprocess.run( result = subprocess.run(
f"{PYTHON_PATH} {args}", f"{PYTHON_PATH} {args}",
shell=True, shell=True,
timeout=timeout, timeout=TASK_TIMEOUT,
capture_output=True, capture_output=True,
text=True, text=True,
encoding="utf-8", encoding="utf-8",
errors="replace" errors="replace",
) )
# 输出执行日志 # 输出执行日志
if result.stdout: if result.stdout:
for line in result.stdout.strip().split('\n'): for line in result.stdout.strip().split("\n"):
if line.strip(): if line.strip():
logging.info(line) logging.info(line)
if result.returncode == 0: if result.returncode == 0:
logging.info(f">>> 任务执行成功") logging.info(f">>> 任务执行成功")
else: else:
logging.error(f">>> 任务执行失败,返回码: {result.returncode}") logging.error(f">>> 任务执行失败,返回码: {result.returncode}")
if result.stderr: if result.stderr:
logging.error(f"错误信息: {result.stderr[:500]}") logging.error(f"错误信息: {result.stderr[:500]}")
except subprocess.TimeoutExpired: except subprocess.TimeoutExpired as e:
logging.error(f">>> 任务执行超时(超过 {timeout} 秒),已强制终止") logging.error(f">>> 任务执行超时(>{TASK_TIMEOUT}s),强制终止")
# 尝试终止进程
if e.process:
try:
e.process.kill()
logging.info(">>> 已终止超时进程")
except:
pass
except Exception as e: except Exception as e:
logging.error(f">>> 任务执行异常: {str(e)}") logging.error(f">>> 任务执行异常: {str(e)}")
logging.error(traceback.format_exc()) logging.error(traceback.format_exc())
finally:
# 确保函数能够正常返回
logging.debug(f">>> run_python 函数执行完成")
# 重新加载任务 # 重新加载任务
@ -515,6 +539,10 @@ def reload_tasks():
trigger=trigger, trigger=trigger,
args=[f"{SCRIPT_PATH} {CONFIG_PATH}"], args=[f"{SCRIPT_PATH} {CONFIG_PATH}"],
id=SCRIPT_PATH, id=SCRIPT_PATH,
max_instances=1, # 最多允许1个实例运行
coalesce=True, # 合并错过的任务,避免堆积
misfire_grace_time=300, # 错过任务的宽限期(秒),超过则跳过
replace_existing=True, # 替换已存在的同ID任务
) )
if scheduler.state == 0: if scheduler.state == 0:
scheduler.start() scheduler.start()
@ -533,7 +561,7 @@ def reload_tasks():
def init(): def init():
global config_data, task_plugins_config_default global config_data, task_plugins_config_default
logging.info(f">>> 初始化配置") logging.info(">>> 初始化配置")
# 检查配置文件是否存在 # 检查配置文件是否存在
if not os.path.exists(CONFIG_PATH): if not os.path.exists(CONFIG_PATH):
if not os.path.exists(os.path.dirname(CONFIG_PATH)): if not os.path.exists(os.path.dirname(CONFIG_PATH)):
@ -571,6 +599,8 @@ def init():
if __name__ == "__main__": if __name__ == "__main__":
init() init()
reload_tasks() reload_tasks()
logging.info(">>> 启动Web服务")
logging.info(f"运行在: http://{HOST}:{PORT}")
app.run( app.run(
debug=DEBUG, debug=DEBUG,
host=HOST, host=HOST,

View File

@ -128,7 +128,6 @@ class Config:
task_plugins_config[module_name] = plugin.default_task_config task_plugins_config[module_name] = plugin.default_task_config
except (ImportError, AttributeError) as e: except (ImportError, AttributeError) as e:
print(f"载入模块 {module_name} 失败: {e}") print(f"载入模块 {module_name} 失败: {e}")
print()
return plugins_available, plugins_config, task_plugins_config return plugins_available, plugins_config, task_plugins_config
def breaking_change_update(config_data): def breaking_change_update(config_data):