2013-01-24 148 views
2

使用Timer類並重新啓動可調用中的定時器是在python中後臺運行週期性定時器的標準方法。python中的週期性定時器,小週期

這有兩大缺點:

  • 它是不是真的週期性:定時器的設置,...
  • 它每期

創建一個新的線程是否有替代Timer類?我看了一下sched類,但是在MainThread中運行會阻塞它,並且不建議在多線程環境中運行它。

如何在Python中使用高頻週期性定時器(100 ms週期),例如在收集批量數據以發送到數據庫時定期清空文檔隊列?

+2

不這樣做,時間是不好的「事件」對於這樣的事情,只是使用隊列和計數的項目/大小閾值,以確定何時需要推送數據。 – drahnr

+0

大小本身不會削減它。假設我的閾值是10個文檔,並且我將9個文檔放入隊列中。我沒有更多的數據,只有9個文件。但是由於沒有達到閾值,數據將不會被推送。因此,要確保在最大時間範圍內推送短的突發數據,需要確定大小和時間間隔的組合。這就是我正在使用的:一個隊列和一個週期性的計時器。或者你有其他建議嗎? – dangonfast

+0

Threashold隊列中**字節**的總數。 – drahnr

回答

4

我想出了以下選擇:

import threading 
import time 

class PeriodicThread(StoppableThread): 
    '''Similar to a Timer(), but uses only one thread, stops cleanly and exits when the main thread exits''' 

    def __init__ (self, period, callable, *args, **kwargs): 
     super(PeriodicThread, self).__init__() 
     self.period = period 
     self.args  = args 
     self.callable = callable 
     self.kwargs = kwargs 
     self.daemon = True 

    def run(self): 
     while not self.stopped(): 
      self.callable(*self.args, **self.kwargs) 
      time.sleep(self.period)