Using Countdown Timer To Jump Out Of While Loop Python
I'll just get to the code to show you, I'm trying to stop my while loop when my timer is over. Is there a way to do that? from threading import Timer def run(timeout=30, runs):
Solution 1:
Changes
- When your timer expires, you need to change the state so that when
over
is invoked, it will returnTrue
. Right now, I keep that in global state for simplicity. You will want to change this at some point. - Also, you had a logic error in your while loop condition. We need to make sure it still has runs and is not over.
#!/usr/bin/env python
from threading import Timer
globalIsOver = False
def run(runs, timeout=30):
timer(timeout)
while runs > 0 and not over():
#Do something
print "start looping"
print 'Exited run function.'
def timer(time):
t = Timer(time, setOver)
print "timer started"
t.start()
def setOver():
global globalIsOver
print '\nSetting globalIsOver = True'
globalIsOver = True
def over():
global globalIsOver
print 'returned = ' + str(globalIsOver)
return globalIsOver
run(100000000, timeout=2)
This returns the following after the 2 seconds have expired:
...
start looping
returned = False
start looping
returned = False
start looping
returned = False
Setting globalIsOver = True
start looping
returned = True
Exited run function.
Post a Comment for "Using Countdown Timer To Jump Out Of While Loop Python"