2017-07-07 22 views
1

這裏是代碼的骨架:我想100次運行do_something如何設置由LoopingCall調度的功能的調用次數?

from twisted.internet import reactor 
from twisted.internet.task import LoopingCall 

def do_something(): 
    print "Doing something..." 

def process_result(): 
    print "Processing result..." 

def loop(): 
    LoopingCall(do_something).start(1) 

reactor.callWhenRunning(loop) 
reactor.run() 

在我的代碼,在那之後我會打電話process_result做什麼它的名字表示。

在我發現了一個withCount的文件,但是我感到困惑「,因爲它是一次調用這應該發生」和「計數通常是1」在裏面。 (使用LoopingCall調用一個函數,一旦有什麼意義,我認爲我誤解了,但什麼是正確的解釋??)

我想知道:是withCount使用正確的事情嗎?如果是,有人可以提供一個具體的例子嗎?

回答

2

withCount爲LoopingCall錯過迭代時提供有用的信息。例如,如果間隔爲1,但函數需要5秒,函數應該調用的次數爲5.但是,在您的示例中,函數幾乎立即返回(並且不是延遲),所以它會始終爲1

from twisted.internet import reactor 
from twisted.internet.task import LoopingCall 

def do_something(count): 
    print "Doing something..." + str(count) 

def process_result(): 
    print "Processing result..." 

def loop(): 
    LoopingCall.withCount(do_something).start(1) 

reactor.callWhenRunning(loop) 
reactor.run() 

您需要檢查的次數的函數被調用,並使用lc.stop當您達到指定次數。如果你不想在do_something中引入額外的邏輯,你可以創建一個包裝類。

from twisted.internet import reactor 
from twisted.internet.task import LoopingCall 

def do_something(): 
    print "Doing something..." 

def process_result(): 
    print "Processing result..." 

def loop(): 
    LoopingCallWithCounter(5, do_something).lc.start(1) 

class LoopingCallWithCounter: 
    def __init__(self, count, f, *a, **kw): 
     self.i = 0 
     def wrapper(): 
      if self.i >= count: 
       self.lc.stop() 
      else: 
       f(*a, **kw) 
       self.i += 1 
     self.lc = LoopingCall(wrapper) 

reactor.callWhenRunning(loop) 
reactor.run() 

最後,由於lc.start回報時lc.stop被稱爲延遲,你可以簡單地使用addCallback(process_result)做後期處理。請注意0​​應該有一個參數。 「

+1

」withCount只有在您希望調用的函數比間隔長時纔有用。「 < - 不完全。 LoopingCall可能會遺漏迭代的其他原因。例如,您的進程中的某些其他代碼正在運行很長時間。 –

+0

的確如此,感謝@ Jean-PaulCalderone編輯。 – lamba