Python3.6个并行重复定时器或多个定时器

Python3.6 parallel repeat timer or multiple timer

我的代码在这里。

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
...   

或者有没有其他方法可以使用线程和定时器来周期性并行迭代?

或者如何使用多个定时器?

当你编码时:

threading.Timer(10,checkMinute(num)).start()

您将首次调用 checkMinute(num)return 值 指定为 10 秒后调用的函数,即 None .这应该更接近于:

threading.Timer(10, checkMinute, args=(num,)).start()

但是你想先把上面的做成守护线程。而且不需要TimerStart。所以请尝试以下操作:

import threading
import time

def checkMinute(num):
    print('check', num)
    # other python code....
    startTimer(num)

def startTimer(num):
    t = threading.Timer(10, checkMinute, args=(num,))
    t.daemon = True
    t.start()
    
if __name__== '__main__':
    startTimer(1)
    startTimer(2)
    startTimer(3)
    time.sleep(1000)
    # or instead of sleeping:
    #input('Hit enter to quit...\n')