在我的一个项目中,我注意到一个问题schedule:
- 我有几个函数在单独的线程中按计划运行(时间不同)
- 但我注意到其中一个函数被同时调用了两次
我抛出了一个最小的例子,问题得到了证实。函数调用确实是重复的
例子:
import threading
import time
import schedule
def run1():
print('run1', threading.current_thread())
time.sleep(2)
def run2():
print('run2', threading.current_thread())
time.sleep(3)
def run_schedule(timeout, run):
schedule.every(timeout).seconds.do(run)
while True:
schedule.run_pending()
time.sleep(1)
threading.Thread(target=run_schedule, args=[5, run1]).start()
threading.Thread(target=run_schedule, args=[7, run2]).start()
结论:
run1 run1 <Thread(Thread-1, started 17828)>
<Thread(Thread-2, started 14008)>
run2 <Thread(Thread-2, started 14008)>
run2 <Thread(Thread-1, started 17828)>
如您所见,每个线程调用一次函数,这会导致run_pending
解决方案是为不同的线程创建单独的
schedule线程。改变功能就足够了:
PS。
我认为为循环分配一个单独的线程
schedule.run_pending()也可以,但是为了使函数在单独的线程中执行,您需要.do(run)将代码包装在一个线程中,例如: