'''
Author: zhoujie2104231 zhoujie@me.com
Date: 2024-03-02 16:20:40
LastEditors: zhoujie2104231 zhoujie@me.com
LastEditTime: 2024-04-10 10:02:34
Description: 

'''
import subprocess
import schedule
import time
from datetime import datetime

import os
 
# 获取当前工作目录
current_directory = os.getcwd()
print("当前工作目录：", current_directory)
# 设置新的工作目录
new_directory = "C:/real_trader"
os.chdir(new_directory) 
# 验证新的工作目录
updated_directory = os.getcwd()
print("已更改为新的工作目录：", updated_directory)


# 定义要启动的文件['real-a.py','real-ag.py','real-rb.py','real-hc.py']
files_to_run = ['real.py']


def run_scripts():
    print("启动程序...")
    for file in files_to_run:
        time.sleep(1)
        # 使用subprocess模块运行命令
        subprocess.Popen(['start', 'cmd', '/k', 'python', file], shell=True)
        print(file)
    print(datetime.now(),'程序重新启动完成，等待明天关闭重启')


def close_scripts():
    print("关闭程序...")
    # 通过创建一个包含关闭指定窗口命令的批处理文件来关闭CMD窗口
    def close_specific_cmd_window(cmd_window_title):
        with open("close_cmd_window.bat", "w") as batch_file:
            batch_file.write(f'@echo off\nfor /f "tokens=2 delims=," %%a in (\'tasklist /v /fo csv ^| findstr /i "{cmd_window_title}"\') do taskkill /pid %%~a')

        # 运行批处理文件
        subprocess.run("close_cmd_window.bat", shell=True)
        

    # 循环关闭所有脚本对应的CMD窗口
    for title in files_to_run:
        close_specific_cmd_window(title)
    print(datetime.now(),'已关闭程序，等待重新运行程序')



# 设置定时任务，关闭程序
schedule.every().day.at("15:30").do(close_scripts)
schedule.every().day.at("03:00").do(close_scripts)

# 设置定时任务，启动程序
schedule.every().day.at("08:55").do(run_scripts)
schedule.every().day.at("20:55").do(run_scripts)



# 保持脚本运行，等待定时任务触发
    #240884432
while True:
    schedule.run_pending()
    time.sleep(1)
    #240884432
