Reputation: 93
My code is here.
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)
When start it first, waiting 10 second is worked, so after 10 seconds later timer is start.
But second start in checkMinute, it not wait and only num=1 are activated, 2 and 3 are not.
Console log is like this.
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
...
And finally error occur.
Fatal Python error: Cannot recover from stack overflow.
Current thread 0x00003a2c (most recent call first):
How do I make sure to keep the wait time when running the second time in checkMinute?
May console log like this.
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
...
Or Is there other way to use a thread and a timer to periodically iterate in parallel?
Or How to use multiple timer?
Upvotes: 1
Views: 727
Reputation: 44313
When you code:
threading.Timer(10,checkMinute(num)).start()
You are specifying as the function to be invoked after 10 seconds the return value from first calling checkMinute(num)
, which is None
. This should be closer to:
threading.Timer(10, checkMinute, args=(num,)).start()
But you want to first make the above a daemon thread. And there is no need for TimerStart
. So try the following:
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')
Upvotes: 2