2015-04-20 131 views
0

我發現了一個解決方案,每N秒週期執行一個函數。定期在線程中執行一個函數

import threading; 

def do_every (interval, worker_func, iterations = 0): 
    if iterations != 1: 
    threading.Timer (
     interval, 
     do_every, [interval, worker_func, 0 if iterations == 0 else iterations-1] 
    ).start(); 

    worker_func(); 

def print_hw(): 
    print "hello world"; 

def print_so(): 
    print "stackoverflow" 


# call print_so every second, 5 times total 
do_every (1, print_so, 5); 

# call print_hw two times per second, forever 
do_every (0.5, print_hw); 

當我們此刻的執行執行該代碼就開始打印的「Hello World」和「計算器」(在時間= 0秒)。什麼是可能的方式,使其打印時間= 1秒和時間= 0.5秒(不是開始時間= 0秒)不使用時間。睡眠

回答

1

我會真的猶豫,每隔一次產生一個新的TimerTimer延伸Thread,並且沒有人希望每隔幾秒就開始一個新線程。

如果我們看一下Python的源代碼,我們可以爲Timer類提供我們自己的實現。我不知道Python,因此可能有一種擴展類的方法,而不是基本上覆制它的所有代碼。

Timer類使用Event(也在threading模塊中)等待指定的時間量。

import threading; 
from threading import Thread; 
from threading import Event; 

#Extended from a class written by Itamar Shtull-Trauring 
class MultiTimer(Thread): 
    def __init__(self, interval, function, count = 0, args=None, kwargs=None): 
     Thread.__init__(self) 
     self.interval = interval 
     self.function = function 
     self.args = args if args is not None else [] 
     self.kwargs = kwargs if kwargs is not None else {} 
     self.finished = Event() 
     self.count = count 
     self.infinite = count == 0 

    def cancel(self): 
     """Stop the timer if it hasn't finished yet.""" 
     self.finished.set() 

    def run(self): 
     while not self.finished.is_set(): 
      self.finished.wait(self.interval) 
      if not self.finished.is_set(): 
       self.function(*self.args, **self.kwargs) 
       self.decrementCount() 

    def decrementCount(self): 
     if not self.infinite: 
      self.count -= 1 
      if self.count == 0: 
       self.finished.set() 

def hello(): 
    print "hello, world" 

#prints "hello, world" 3 times, at time = 2, 4, 6 
t = MultiTimer(2.0, hello, 3) 
t.start(); 

#never stops printing "hello, world" every 2 seconds 
u = MultiTimer(2.0, hello) 
u.start(); 
+0

「持續時間」是一個比「count」更好的變量名稱,用於記錄。我將暫緩編輯答案,因爲我確定有一個比'MultiTimer'更好的名字。 –

相關問題