一:twisted支持两种方式的定时器,阻塞与不阻塞都支持
阻塞:Python的sleep() 线程会阻塞住,不往下执行了
非阻塞:reactor.callLater(time, func, args) 并不阻塞程序
二:twisted中常见定时器
1:一次性定时器 callLater
from twisted.internet import reactor
def f(s):
print "this will run 3.5 seconds after it was scheduled: %s" % s
t = reactor.callLater(3.5, f, "hello, world")
#t.cancel()
reactor.run()
callLater位于所有reactor的基类 ReactorBase 中
2:想要获取定时器执行函数的结果
from twisted.internet import task
from twisted.internet import reactor
def f(s):
return "This will run 3.5 seconds after it was scheduled: %s" % s
d = task.deferLater(reactor, 3.5, f, "hello, world")
def called(result):
print result
#d.cancel()
d.addCallback(called)
deferLater创建一个Deferred 并作延时调用
3:循环执行
from twisted.internet import task
from twisted.internet import reactor
def onTimer():
print "a second has passed"
l = task.LoopingCall(onTimer)
l.start(1.0,False)
#l.stop()
reactor.run()
start第二个参数看源码就知道是啥意思了
twisted的定时器 使用起来还是蛮方便的。。。
三:测试
可以发现 1ms级别的定时器 不准确 10ms级别的还凑合