【问题标题】:Infinite loop preventing root.mainloop() from executing- Python阻止 root.mainloop() 执行的无限循环 - Python
【发布时间】:2022-01-24 03:59:41
【问题描述】:

嘿,伙计们,这可能很愚蠢,但我无法找到解决方法...我试图每天运行我的 python 代码,并且我使用调度来执行此操作。但是,它会阻止到达root.mainloop(),因为之前存在无限循环。这是网站https://pypi.org/project/schedule/ 如果有更好的方法来“安排”我的代码在某些日子的某个时间运行,我将不胜感激!这是下面的示例代码。

def job():
    print("I am doing this job!")


schedule.every().monday.at("11:21").do(job)
schedule.every().tuesday.at("14:00").do(job)
schedule.every().wednesday.at("22:00").do(job)
schedule.every().thursday.at("14:00").do(job)
schedule.every().friday.at("14:00").do(job)

while True:
    schedule.run_pending()
    time.sleep(1)
    

root.mainloop()

谢谢!

【问题讨论】:

  • 官方文档中有一个example在子线程中运行while循环。

标签: python tkinter automation scheduler


【解决方案1】:

官方文档中有example在子线程中运行while循环。

下面是另一个简单的例子:

import threading
...

def check_schedule():
    while True:
        schedule.run_pending()
        time.sleep(1)

threading.Thread(target=check_schedule, daemon=True).start()

root.mainloop()

如果job()不是长时间运行的任务,可以使用after()代替while循环:

...

def check_schedule():
    schedule.run_pending()
    root.after(1000, check_schedule)

check_schedule() # start the loop

root.mainloop()

【讨论】:

  • 感谢您的回复。我应该在哪里输入代码行 schedule.every().thursday.at("09:28").do(send_email()) 以便它在特定时间发送电子邮件?
  • @kyle 与您安排job()的方式相同。
猜你喜欢
  • 2015-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多