注意 首次启动时立即执行一次任务,之后的任务会按照设置好的实际执行。
import threading
import datetime
import time
import subprocess
import os
sch_hour = 15
# 要执行的脚本路径
script_path = r'.'
script_file = os.path.join(script_path,'NR_station_warning.py')
def run_script():
# 使用subprocess模块运行脚本
subprocess.Popen(['python', script_file], stdout=subprocess.PIPE)
def schedule_daily_task():
# 获取当前时间
now = datetime.datetime.now()
# 设置每天15点为目标时间 0时区7点
target_time = now.replace(hour= sch_hour, minute=25, second=0, microsecond=0)
# 如果当前时间已经超过15点,则设置目标时间为下一天的15点
if now > target_time:
target_time += datetime.timedelta(days=1)
# 计算需要等待的秒数
wait_seconds = (target_time - now).total_seconds()
# 等待直到目标时间
time.sleep(wait_seconds)
# 执行脚本
run_script()
# 创建并启动一个新的线程来重复这个过程
threading.Thread(target=schedule_daily_task).start()
# 启动调度任务
threading.Thread(target=schedule_daily_task).start()