2016-11-30 96 views
2

以下程序僅打印一次hello world,而不是每5秒打印一次字符串。定時器只在python中運行一次

from threading import Timer; 

class TestTimer: 

    def __init__(self): 
     self.t1 = Timer(5.0, self.foo); 

    def startTimer(self): 
     self.t1.start(); 

    def foo(self): 
     print("Hello, World!!!"); 

timer = TestTimer(); 
timer.startTimer(); 


         (program - 1) 

但是下面的程序每5秒打印一次字符串。

def foo(): 
    print("World"); 
    Timer(5.0, foo).start(); 

foo(); 

         (program - 2) 

爲什麼(程序-1)不會每5秒打印一次字符串?以及如何使(程序-1)每5秒連續打印一次字符串。

+0

你爲什麼要在一個額外的類中包裝它以開始?這是必要的嗎? – nlsdfnbch

回答

1

(程序-2)每5秒打印一次字符串,因爲它正在遞歸地調用它自己。正如你所看到的,你可以在自己內部調用foo()函數,這是因爲它起作用的原因。

如果你想打印每5秒一個字符串 - 使用一個類你可以(方案1)(但它不是一個真正的好習慣!):

from threading import Timer 

class TestTimer: 
    def boo(self): 
     print("World") 
     Timer(1.0, self.boo).start() 

timer = TestTimer() 
timer.boo() 
0

正如已經指出的那樣,你「再調用foo()遞歸:

def foo(): 
    print("World"); 
    Timer(5.0, foo).start(); # Calls foo() again after 5s and so on 

foo(); 

在你的問題,你已經創建了一個包裝圍繞threading.Timer - 我建議你簡單地繼承它:

from threading import Timer 

class TestTimer(Timer): 

    def __init__(self, i): 
     self.running = False 
     super(TestTimer, self).__init__(i, self.boo) 

    def boo(self): 
     print("Hello World") 

    def stop(): 
     self.running = False 
     super(TestTimer, self).stop() 

    def start(): 
     self.running = True 
     while self.running: 
      super(TestTimer, self).start() 

t = TestTimer(5) 
t.start()