用python在指定时间运行某段代码,并在某段时间推出代码运行。

 代码逻辑:

情况1:while true 会不断循环代码,直到 if statement的“当前时间” 等于 end date,则会打印 代码停止的时间。 

情况2:第一个if statement的“当前时间”不等于end date 则会 跳去第二个 if statement,并执行既定的时间条件。以此循环,直到当前的时间等于end date

重点:time.sleep(61)秒是为了防止代码在一分钟内反复运行。因此会让代码休息61秒,然后就可以有执行一次代码的效果了

#必须要用这个package,如果使用 import datetime 会出现代Error。
from datetime import datetime

while True:
    time_now = time.strftime("%H:%M", time.localtime())  # control the day in hour, such as 9:10
    today_date = datetime.today().date()#control the date, such as 2021-8-13
    end_date = '2021/08/17'#set the end date 
    end_date = datetime.strptime(end_date, '%Y/%m/%d')#translate to datetime format
    end_date = datetime.date(end_date)# translate to the format that fits with the time_now variable
    
    if today_date < end_date:  #try to stop the coding base on the given end date     
        if time_now == "12:00": #try to run the code in the specific time
            call_api()
            time.sleep(61) # need to sleep 61 seconds if you want to run the code one time only
        elif time_now == "13:00":
            call_api()
            time.sleep(61) # need to sleep 61 seconds if you want to run the code one time only
        elif time_now == "18:00":
            call_api()
            time.sleep(61) # need to sleep 61 seconds if you want to run the code one time only
       
        elif time_now =="20:00":
            call_api()
            time.sleep(61) # need to sleep 61 seconds if you want to run the code one time only
        elif time_now =="23:59":
            call_api()
            time.sleep(61) # need to sleep 61 seconds if you want to run the code one time only
    
    else:
# to better understand when the coding stopped, then it needs to show the stop time message 
        print("The coding is stoped" + " & " + "stop date:%s & stop time:%s" % (today_date,time_now ))
        break

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值