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

2024-09-28 15:14:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我的密码在这里

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

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

或者如何使用多重定时器


Tags: truetargetdefcheckargsthreadstartnum
1条回答
网友
1楼 · 发布于 2024-09-28 15:14:37

编写代码时:

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

您正在将第一次调用checkMinute(num)返回值指定为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')

相关问题 更多 >