python中延时函数_推迟python中的函数

要在延迟后执行函数或使用事件循环(无线程)在给定的秒数内重复函数,您可以:

Tkinter的

#!/usr/bin/env python

from Tkinter import Tk

def foo():

print("timer went off!")

def countdown(n, bps, root):

if n == 0:

root.destroy() # exit mainloop

else:

print(n)

root.after(1000 / bps, countdown, n - 1, bps, root) # repeat the call

root = Tk()

root.withdraw() # don't show the GUI window

root.after(4000, foo) # call foo() in 4 seconds

root.after(0, countdown, 10, 2, root) # show that we are alive

root.mainloop()

print("done")

产量

10

9

8

7

6

5

4

3

timer went off!

2

1

done

GTK

#!/usr/bin/env python

from gi.repository import GObject, Gtk

def foo():

print("timer went off!")

def countdown(n): # note: a closure could have been used here instead

if n[0] == 0:

Gtk.main_quit() # exit mainloop

else:

print(n[0])

n[0] -= 1

return True # repeat the call

GObject.timeout_add(4000, foo) # call foo() in 4 seconds

GObject.timeout_add(500, countdown, [10])

Gtk.main()

print("done")

产量

10

9

8

7

6

5

4

timer went off!

3

2

1

done

扭曲

#!/usr/bin/env python

from twisted.internet import reactor

from twisted.internet.task import LoopingCall

def foo():

print("timer went off!")

def countdown(n):

if n[0] == 0:

reactor.stop() # exit mainloop

else:

print(n[0])

n[0] -= 1

reactor.callLater(4, foo) # call foo() in 4 seconds

LoopingCall(countdown, [10]).start(.5) # repeat the call in .5 seconds

reactor.run()

print("done")

产量

10

9

8

7

6

5

4

3

timer went off!

2

1

done

ASYNCIO

Python 3.4 为异步IO 引入了新的临时API - asyncio模块:

#!/usr/bin/env python3.4

import asyncio

def foo():

print("timer went off!")

def countdown(n):

if n[0] == 0:

loop.stop() # end loop.run_forever()

else:

print(n[0])

n[0] -= 1

def frange(start=0, stop=None, step=1):

while stop is None or start < stop:

yield start

start += step #NOTE: loss of precision over time

def call_every(loop, seconds, func, *args, now=True):

def repeat(now=True, times=frange(loop.time() + seconds, None, seconds)):

if now:

func(*args)

loop.call_at(next(times), repeat)

repeat(now=now)

loop = asyncio.get_event_loop()

loop.call_later(4, foo) # call foo() in 4 seconds

call_every(loop, 0.5, countdown, [10]) # repeat the call every .5 seconds

loop.run_forever()

loop.close()

print("done")

产量

10

9

8

7

6

5

4

3

timer went off!

2

1

done

注意:这些方法之间的界面和行为略有不同。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值