我的密码在这里
import threading
def checkMinute(num):
print('check ' + str(num))
# other python code....
threading.Timer(10, checkMinute(num)).start() # repeat until ctrl + c
def TimerStart(num):
threading.Timer(10,checkMinute(num)).start()
if __name__=="__main__":
t1=threading.Thread(target=TimerStart,args=(10, 1)) # interval is 10 seconds
t2=threading.Thread(target=TimerStart,args=(10, 2))
t3=threading.Thread(target=TimerStart,args=(10, 3))
t1.daemon=True # For stop when ctrl+c
t2.daemon=True
t3.daemon=True
t1.start()
t2.start()
t3.start()
time.sleep(1000)
当第一次启动时,等待10秒是有效的,所以10秒后计时器启动
但在checkMinute中第二次启动时,它不等待,只有num=1被激活,2和3不被激活
控制台日志如下所示
check 1 # 00:00:00 -> it not wait 10 second. and only 1 is active.
check 1 # 00:00:00
check 1 # 00:00:00
check 1 # 00:00:00
check 1 # 00:00:00
...
最后出现错误
Fatal Python error: Cannot recover from stack overflow.
Current thread 0x00003a2c (most recent call first):
如何确保在checkMinute中运行第二次时保持等待时间
我可以这样记录
check 1 # 00:00:00
check 2 # 00:00:00
check 3 # 00:00:00
check 2 # 00:00:10
check 1 # 00:00:10
check 3 # 00:00:10
check 1 # 00:00:20
check 3 # 00:00:20
check 2 # 00:00:20
check 3 # 00:00:30
...
或者有没有其他方法可以使用线程和计时器来定期并行迭代
或者如何使用多重定时器
编写代码时:
您正在将第一次调用
checkMinute(num)
的返回值指定为10秒后要调用的函数,即None
。这应该更接近:但是首先要将上面的线程设置为守护进程线程。而且不需要
TimerStart
。因此,请尝试以下方法:相关问题 更多 >
编程相关推荐