Reputation: 3
I want to set multiple timers (same function) at the same time, but with different ending times. Coding in python 3. My code currently is:
import time
def timer(t):
start = time.time()
stop = False
while not stop:
if time.time()> start+t:
print("I'm done counting to %d" % t)
stop = True
timer(4)
timer(1)
timer(5)
Now I would like it would first print 1, then 4 and finally 5, but instead it runs completely timer(4) and only after that it continues to the next timer. I've heard a bit about multi-threading, but couldn't find a good example how to implement it in my code. Eventually, I would also like to add an option to delay the start of the timer with n seconds. Thanks a lot!
Upvotes: 0
Views: 934
Reputation: 955
If it's just about timers, you can use directly timers, without more complicated multi-threading:
https://docs.python.org/3.8/library/threading.html
https://docs.python.org/3.8/library/threading.html#timer-objects
import threading
def hello():
print("hello, world")
t = Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed
Try this one: (Tested on my machine, Python 3.8.2)
from threading import Timer
def hello(t):
print("Counted to", t)
t1 = Timer(4, hello, [4])
t1.start()
t2 = Timer(1, hello, [1])
t2.start()
t3 = Timer(3, hello, [3])
t3.start()
In order to delay the start, add other timers which call a function that does nothing.
These type of timers are called only once though at the ending time.
Upvotes: 1