先看一个简单的延迟调用(一次定时器)
from twisted.internet import reactor
def f(s):
print "this will run 3.5 seconds after it was scheduled: %s" % s
reactor.callLater(3.5, f, "hello, world")
# f() will only be called if the event loop is started.
reactor.run() react
若是函数的结果很重要或者想知道调用过程当中发生了上面,那么twisted.internet.task.deferLater 属性可以建立一个Deferred 并作一个延时调用:
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.addCallback(called)
reactor.run() 异步
若是您有一个任务须要每隔X秒执行一次,那么咱们使用twisted.internet.task.LoopingCall:
from twisted.internet import task
from twisted.internet import reactor
def runEverySecond():
print "a second has passed"
l = task.LoopingCall(runEverySecond)
l.start(1.0) # call every second
# l.stop() will stop the looping calls
reactor.run() 函数
另外,咱们还能够取消一个任务:
from twisted.internet import reactor
def f():
print "I'll never run."
callID = reactor.callLater(5, f)
callID.cancel() #cancel the task
reactor.run()
全部的任务都是以 reactor.run() 开始的。 oop
与同步模型相比,异步模型的优点在以下状况下会获得发挥:
1.有大量的任务,所以在一个时刻至少有一个任务要运行
2.任务执行大量的I/O操做,这样同步模型就会在由于任务阻塞而浪费大量的时间
3.任务之间相互独立,以致于任务内部的交互不多。 性能