【问题标题】:Python Wait /Pause until specific Time... And stop at end of schedulePython等待/暂停直到特定时间......并在计划结束时停止
【发布时间】:2020-12-03 15:16:58
【问题描述】:

使用以下代码,我试图在上午 9 点 15 分到下午 17 点 30 分之间运行程序;;它应该在晚上 17:30 停止,然后再等到第二天早上 9:15,不会自行结束。

### For experiment sake, I have made the datetime.time(20,26) and (20,28)... 
### You may change it to any of the hours and mins of your time...
### But I am hoping it would start and stop between those times please... 

import time, datetime, pause

def printing_something():
    print("Hello World")  # you can add any func here

day_of_week = datetime.date.today().weekday() # (0=Monday), (5=Saturday) and (6=Sunday)
timer_now = datetime.datetime.now().time()

while True:
    if day_of_week < 5 and (timer_now > datetime.time(20,26) and timer_now < datetime.time(20,28)):
        time.sleep(5 - time.time() % 5)
        printing_something()
    else:
        pause.until(datetime(9, 15, 0))

首先... 这段代码的问题是它在时间开始时没有做任何事情,以防我在计划前一个小时开始......它显示它正在运行,但是当确切时间到来时(例如 20:26hours ,就像上面的代码一样),它只是不打印任何被询问的内容。

其次... 如果我碰巧在预定时间内开始,那么它将开始打印,但它不会在 20:28 小时结束时停止打印,就像它预定停止一样......

那么,问题又来了…… 如果我在白天或晚上的任何时间启动程序,然后离开它......如何让它在上午 9:15 执行并让它在下午 17:30 停止......然后让程序继续运行(但暂停)直到次日上午 9 点 15 分......

(为了更清楚起见,我试图仅在周一至周五之间的市场时间运行......并且部分代码可能不相关,但我是 python 新手,抱歉)

【问题讨论】:

    标签: python-3.x datetime time pause until-loop


    【解决方案1】:

    由于这里没有太多帮助,我已经使用以下代码制定了一个临时解决方法。我在一天开始时手动启动程序执行,然后在晚上 17:30 关闭程序。

    import schedule
    import time
    
    def job():
        print("I'm working...")
    
    schedule.every(5).minutes.do(job)
    schedule.every().day.at("9:15").do(job)
    
    while True:
        schedule.run_pending()
        time.sleep(1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-17
      • 1970-01-01
      • 1970-01-01
      • 2012-12-18
      • 2014-03-23
      • 1970-01-01
      • 1970-01-01
      • 2020-12-10
      相关资源
      最近更新 更多