如何解决我想了解 echedule.every().day.at 如何与另一个线程并行
我需要帮助,我使用 schedule.every().day.at("17:40").do(my_function) 并且我希望我的程序在 schedule.every().day 时正常运行.at("17:40").do(my_function) 到达,它执行相关的函数,但随后它又回到我的循环中并等待另一天等等......我不知道该怎么做,因为我认为日程安排.every().day.at("17:40").do(my_function) 需要 而1: schedule.run_pending() 时间.睡眠(1) 所以我不知道如何更改这 3 个 lignes 以使我的程序正常工作。 谢谢!
解决方法
您必须在单独的 threading 或 multiprocessing 中运行它。
但首先你应该检查 documentation 因为我在 Common Questions
中找到:
How to continuously run the scheduler without blocking the main thread?
他们创建了类 Scheduler
将它放在线程中,您需要运行 run_continuously()
但我用它来创建更短的示例
import schedule
import time
import threading
# --- functions ---
stop_running = threading.Event() # to control loop in thread
def run_continuously(scheduler,interval=1):
#print('starting loop in thread')
while not stop_running.is_set():
schedule.run_pending()
time.sleep(interval)
#print('stoping loop in thread')
def job():
print("I'm working...")
# --- main ---
schedule.every(1).minutes.do(job)
# run schedule in thread
schedule_in_thread = threading.Thread(target=run_continuously,args=(schedule,))
schedule_in_thread.start()
# run other code
#print('starting main loop')
try:
while True:
print("other code")
time.sleep(3)
except KeyboardInterrupt as ex:
print('stoping',ex)
#print('stoping main loop')
# stop schedule in thread
stop_running.set() # to stop loop in `run_continuously`
schedule_in_thread.join() # wait until thread finish
我使用 try/except
和 KeyboardInterrupt
只是为了在按 Ctrl+C 时正常停止程序 - 代码可能会停止线程。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。