如何使 While True Check Forever

How to make While True Check Forever

我这里有这段代码:

from datetime import datetime

lctime = datetime.now().strftime("%H:%M")
openphone = '01:00'
rest = '02:00'
GoOutside = '03:00'
DoSport = '04:00'

while True:
    if lctime == openphone:
        print("You Can Open Phone!")
        
    if lctime == rest:
        print("Take Rest or A Coffe!")
        
    if lctime == GoOutside:
        print("Go Outside, Have fun")
        
    if lctime == DoSport:
        print("Do Some Sport Bro!!")

问题是如果 lctime(本地时间)等于这些时间之一,它永远不会停止打印文本,我使用 break 语句并打印一次文本并关闭程序并且从不检查下一个(永远)

,所以我如何让 True 永远检查 lctime(本地时间)是否等于这些时间之一,如果它等于其中一个,它会打印文本并检查其他时间并继续检查并执行此操作永远.

由于您在 while 循环外声明了变量 lctime,它会在您启动程序时存储该值,并且不会再更改。 您可以在 while 循环中更新它来解决问题

while True:
    lctime = datetime.now().strftime("%H:%M")
    if lctime == openphone:
        print("You Can Open Phone!")
        
    if lctime == rest:
        print("Take Rest or A Coffe!")
        
    if lctime == GoOutside:
        print("Go Outside, Have fun")
        
    if lctime == DoSport:
        print("Do Some Sport Bro!!")

这应该有效。

此外,由于您的 lctime 仅以小时和分钟为单位存储时间,因此 if 语句的任何条件为真,它将连续打印一分钟不间断的行。 为了解决这个问题,我建议你使用某种检查变量

这应该可以修复错误并使 while 循环正常工作。

from datetime import datetime
lctime = ''
openphone = '01:00'
rest = '02:00'
GoOutside = '03:00'
DoSport = '04:00'

while True:
  lctime = datetime.now().strftime("%H:%M")
  
  if lctime == openphone:
      print("You Can Open Phone!")
      break
  elif lctime == rest:
      print("Take Rest or A Coffe!")
      break
  elif lctime == GoOutside:
      print("Go Outside, Have fun")
      break
  elif lctime == DoSport:
      print("Do Some Sport Bro!!")
      break
  else:
      break

我想推荐一种替代的、更惯用的方法来在特定时间安排任务。标准库公开了一个通用调度程序 class(这似乎是一个美化的轮询循环,但至少它会休眠,并且感觉更像是事件驱动的)。

def do_sports():
    print("Do sports")

def check_emails():
    print("Check emails")

def do_homework():
    print("Do homework")


def main():

    from datetime import datetime, timedelta
    import sched
    import time

    today = datetime.now().replace(microsecond=0, second=0, minute=0, hour=0)
    tasks = [
        (do_sports, timedelta(hours=7)),
        (check_emails, timedelta(hours=8, minutes=30)),
        (do_homework, timedelta(hours=9, minutes=12, seconds=59))
    ]

    scheduler = sched.scheduler(time.time, time.sleep)

    for callback, delta in tasks:
        timestamp = (today + delta).timestamp()
        scheduler.enterabs(timestamp, 1, callback)
    scheduler.run()
    
    return 0


if __name__ == "__main__":
    import sys
    sys.exit(main())