Reputation: 31
I have an application where I have to run a command for y number of seconds but only when a condition is met. As soon as time duration is up, then it should move to next line.
Example: Second=10
if i==1:
print("Hello") # for 10 seconds
It should only print hello for 10 seconds and then move on.
How can I achieve this in Python?
Upvotes: 0
Views: 108
Reputation: 46
I would change the previous answer a bit:
import time
if i==1:
starttime=time.time()
while time.time() < (starttime+10):
time.sleep(1) # <-- do not print hello too often !
print("hello")
because otherwise it will print "hello" about 10,345,123 times by my estimate :)
Upvotes: 1
Reputation: 396
Just add a time loop inside your conditional:
import time
if i==1:
starttime=time.time()
while time.time() < (starttime+10):
print("hello")
Upvotes: 1