简体   繁体   中英

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):
    timer(timeout)
    while runs > 0 or over():
        #Do something
        print "start looping"

def timer(time):
    t = Timer(time, over)
    print "timer started"
    t.start()

def over():
    print "returned false"
    return False

As you can see, I'm trying to use the function over() to stop my while loop. Currently, when my time stop, over is returned as false, but it doesn't affect my while loop. I must be doing something wrong.

So what Timer object allows me to do is to pass a function param so that when the timer is over, it calls that function, over() . As over() returns False , it doesn't directly affect the while loop in real time. Will I need a callback to implicitly force the while to be false or is my method of stopping is completly faulty and will not work.

Changes

  • When your timer expires, you need to change the state so that when over is invoked, it will return True . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM