python设置定时任务

# -*- coding: utf-8 -*-
"""
Created on Thu Jan 16 11:01:57 2025

@author: IGEN
"""

import threading
import datetime
import time
import subprocess
import os

def write_log(concent):
    try:
        with open("./station_warning.log", 'a') as f:
            f.write(concent + '\n')
    except:
        with open("./station_warning.log", 'a') as f:
            f.write(concent + '\n')

# 设置几点执行
sch_hour = 12
# 要执行的脚本路径
script_path = r'.'
script_file = os.path.join(script_path,'NR_station_warning.py')

try:

    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= 10, 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()

except Exception as e:
    
    print(e)
    write_log(e)

# 启动调度任务
threading.Thread(target=schedule_daily_task).start()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值