import subprocess import sys import os from pathlib import Path from logger_config import setup_logger # 设置日志记录器 logger = setup_logger('service_runner') def run_in_background(): """在后台运行定时任务""" logger.info("=" * 50) logger.info("开始启动后台定时任务") logger.info("=" * 50) script_path = Path(__file__).parent / "scheduler.py" pid_file = Path(__file__).parent / "scheduler_pid.txt" logger.info(f"脚本路径: {script_path}") logger.info(f"PID文件路径: {pid_file}") logger.info(f"当前工作目录: {os.getcwd()}") # 检查脚本文件是否存在 if not script_path.exists(): logger.error(f"脚本文件不存在: {script_path}") return False # 检查是否已经有PID文件 if pid_file.exists(): logger.warning(f"发现已存在的PID文件: {pid_file}") try: with open(pid_file, 'r') as f: old_pid = f.read().strip() logger.warning(f"已存在的进程ID: {old_pid}") # 检查进程是否还在运行 try: import psutil if psutil.pid_exists(int(old_pid)): logger.warning(f"进程 {old_pid} 仍在运行,请先停止它") return False else: logger.info(f"进程 {old_pid} 已不存在,删除旧的PID文件") pid_file.unlink() except ImportError: logger.warning("无法检查进程状态,建议手动确认") return False except Exception as e: logger.error(f"读取PID文件失败: {str(e)}") pid_file.unlink() # 删除损坏的PID文件 # 使用pythonw.exe在后台运行(无窗口) pythonw_path = sys.executable.replace('python.exe', 'pythonw.exe') logger.info(f"Python解释器路径: {sys.executable}") logger.info(f"Pythonw路径: {pythonw_path}") if not os.path.exists(pythonw_path): logger.warning(f"pythonw.exe不存在,使用python.exe替代") pythonw_path = sys.executable try: logger.info("正在启动后台进程...") process = subprocess.Popen([pythonw_path, str(script_path)], cwd=str(Path(__file__).parent), creationflags=subprocess.CREATE_NO_WINDOW) logger.info(f"后台进程启动成功,进程ID: {process.pid}") # 保存进程ID到文件 with open(pid_file, 'w') as f: f.write(str(process.pid)) logger.info(f"进程ID已保存到: {pid_file}") logger.info("=" * 50) logger.info("后台定时任务启动完成") logger.info("=" * 50) return True except Exception as e: logger.error(f"启动后台进程失败: {str(e)}") logger.error(f"错误类型: {type(e).__name__}") import traceback logger.error(f"异常堆栈: {traceback.format_exc()}") return False if __name__ == "__main__": try: success = run_in_background() if success: logger.info("程序执行完成") else: logger.error("程序执行失败") exit(1) except Exception as e: logger.error(f"程序执行过程中出现未捕获的异常: {str(e)}") logger.error(f"异常类型: {type(e).__name__}") import traceback logger.error(f"异常堆栈: {traceback.format_exc()}") exit(1)