feat: 添加定时任务后台运行和停止功能
新增service_runner.py用于后台运行定时任务,使用pythonw.exe实现无窗口运行 新增stop_scheduler.py用于停止后台定时任务进程 调整scheduler.py中的任务执行时间
This commit is contained in:
parent
84288fc66b
commit
546ca9dfe2
@ -22,7 +22,7 @@ def run_sendmsg():
|
||||
def main():
|
||||
"""主函数 - 设置定时任务"""
|
||||
# 每天17:30执行任务
|
||||
schedule.every().day.at("17:27").do(run_sendmsg)
|
||||
schedule.every().day.at("17:40").do(run_sendmsg)
|
||||
|
||||
print(f"[{datetime.now()}] 定时任务已启动,将在每天17:30执行sendmsg.py")
|
||||
print("按Ctrl+C停止程序")
|
||||
|
||||
20
service_runner.py
Normal file
20
service_runner.py
Normal file
@ -0,0 +1,20 @@
|
||||
import subprocess
|
||||
import sys
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
def run_in_background():
|
||||
"""在后台运行定时任务"""
|
||||
script_path = Path(__file__).parent / "scheduler.py"
|
||||
|
||||
# 使用pythonw.exe在后台运行(无窗口)
|
||||
pythonw_path = sys.executable.replace('python.exe', 'pythonw.exe')
|
||||
|
||||
subprocess.Popen([pythonw_path, str(script_path)],
|
||||
cwd=str(Path(__file__).parent),
|
||||
creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
|
||||
print("定时任务已在后台启动")
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_in_background()
|
||||
25
stop_scheduler.py
Normal file
25
stop_scheduler.py
Normal file
@ -0,0 +1,25 @@
|
||||
import subprocess
|
||||
import sys
|
||||
import os
|
||||
|
||||
def stop_scheduler():
|
||||
"""停止定时任务进程"""
|
||||
try:
|
||||
# 查找并结束scheduler.py进程
|
||||
result = subprocess.run(['tasklist', '/FI', 'IMAGENAME eq pythonw.exe', '/FO', 'CSV'],
|
||||
capture_output=True, text=True)
|
||||
|
||||
if 'scheduler.py' in result.stdout:
|
||||
# 结束包含scheduler.py的pythonw进程
|
||||
subprocess.run(['taskkill', '/F', '/IM', 'pythonw.exe'], check=True)
|
||||
print("定时任务已停止")
|
||||
else:
|
||||
print("未找到运行中的定时任务")
|
||||
|
||||
except subprocess.CalledProcessError as e:
|
||||
print(f"停止进程时出错: {e}")
|
||||
except Exception as e:
|
||||
print(f"发生错误: {e}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
stop_scheduler()
|
||||
Loading…
x
Reference in New Issue
Block a user