python超时跳出循环,使用倒数计时器跳出while循环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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值