先看一個簡單的延遲調用(一次定時器)
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.任務之間相互獨立,以致於任務內部的交互不多。 性能