import time 
import subprocess
from datetime import datetime, timedelta

def check_running_process():
    """检查是否已经有相同的进程在运行"""
    command = "ps -ef | grep 'python3 btc_utxos_lyq2.py' | grep -v grep"
    process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
    output, _ = process.communicate()
    return bool(output)  # 如果找到输出，表示有相同的进程在运行

def run_script_for_date(target_date):
    """运行指定日期的脚本"""
    command = f"python3 btc_utxos_lyq2.py {target_date}"
    result=subprocess.run(command, shell=True)
    if result.returncode != 0:
        raise RuntimeError(f"Script failed for date {target_date}")

def main():
    # 从7月10日开始
    start_date = datetime(2024, 12, 16)
    end_date = datetime.utcnow()  # 今天的日期

    current_date = start_date
    a=datetime(2024,12,18)
    if current_date == a:
        current_date += timedelta(days=1)
    else:
        while current_date <= end_date:
            target_date_str = current_date.strftime('%Y-%m-%d')

            # 检查是否已经有相同的进程在运行
            if check_running_process():
                print(f"已经有相同的进程在运行，等待完成再运行 {target_date_str} 的任务。")
                time.sleep(60)  # 等待60分钟后再检查
                continue

            # 运行脚本
            print(f"开始运行 {target_date_str} 的任务。")
            try:
                run_script_for_date(target_date_str)
                print(f"{target_date_str} 的任务运行完成。")

                # 处理下一天的数据
                current_date += timedelta(days=1)
            except RuntimeError as e:
                print(f"Error occurred: {e}. Retrying {target_date_str}.")
                time.sleep(60)

if __name__ == "__main__":
    main()