添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
冲动的楼梯  ·  spring springboot ...·  1 月前    · 
勤奋的手电筒  ·  django admin.py ...·  2 月前    · 
乐观的滑板  ·  python3 ...·  1 年前    · 

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.

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 Timerdef run(timeout=30, runs):timer(timeout)while runs &...
一般在线程中,我们运用的是 定时器 计时器 ,但是 计时器 用来统计运行 时间 的效果不大,因为单用 计时器 还要配合很多的if判断,所以习惯把 计时器 封装成一个函数运行 超时 装置 1/ Python 中的 定时器 可以理解成每隔多久运行一次函数 在函数中可以这样 使用 : import time from threading import Timer def test(): print('111') time.sleep(5) s='a' print('aaa') return s t=Timer
在上一篇《手把手陪您学 Python 》16——循环语句while中,我们学习了 while循环 使用 方法,并应用 while循环 ,实现了“石头剪刀布”游戏的循环运行。 虽然这个版本已经比第一个版本方便了很多,但还是缺少点游戏的感觉,如果要能实现我们平时所说的“三局两胜”或者“五局三胜”就好了。那么,今天我们就学习一种新的方法,看看利用这种方法,能否实现多局定胜负的功能。 今天,我们要学习方法叫做循环...