2012-02-28 37 views
1

我創建了一個jabberbot類,我想安排廣播消息。我沒有太多的線程經驗(使用任何語言),但我很難用Python來理解這個概念。執行功能每隔X秒級初始化

我lattest嘗試使用threading.timer是這樣的:

class myBot(JabberBot): 
    def __init__(self, jid, password, res = none): 
     autoNotify() 

     def autoNotify(): 
      #Send timed message 
      self.send('[email protected]','cooool message text!') 
      #set/reset timer 
      t = Timer(05,self.autoNotify) 
      t.start() 

這裏的問題是,它不斷派生新的線程,直到它最終死亡。我已經閱讀了很多關於如何使用第三方庫,消息隊列和扭曲的示例,但我的問題僅僅是這樣 - 真的沒有簡單的方法來產生單個異步線程嗎?

回答

1

Yes, there is

但是,你真的應該不產卵在構造函數中的線程。相反,提供一個run方法並從threading.Thread繼承,這將使公衆可用的start方法可用於啓動通知循環。事情是這樣的:

import threading 
import time 

class myBot(JabberBot, threading.Thread): 
    def __init__(self, jid, password, res = none): 
    threading.Thread.__init__(self) 

    def run(self): 
    while True: 
     self.autoNotify() 
     time.sleep(5) # wait 4 seconds 

    def autoNotify(self): 
    self.send('[email protected]','cooool message text!') 

使用這樣的:

myBot(...).start() 

如果您不能或不想使用多重繼承出於某種原因,你也可以做這樣的事情:

class myBot(JabberBot): 
    def start(self): 
    threading.Thread(target=self.autoNotifyLoop).start() 

    def autoNotifyLoop(self): 
    while True: 
     self.autoNotify() 
     time.sleep(5) # wait 4 seconds 

    def autoNotify(self): 
    self.send('[email protected]','cooool message text!') 

您還可以創建一個功能,最大的 「方便」:

def call_async(func, *args, **kw): 
    threading.Thread(target=func, args=args, kwargs=kw).start() 

def do_something(msg): 
    print msg 

call_async(do_something, "Don't overuse threads!") 
+0

真棒例子,謝謝!你有可能擴展爲什麼你不應該在構造函數中產生線程?我想我已經明白爲什麼了,但是我愛從知道比我更好的人那裏知道。 – HurnsMobile 2012-02-28 00:47:10

+0

@HurnsMobile:這是一條簡單的規則:除初始化之外,不要在構造函數中做任何事情。你的API的用戶不希望構造函數有副作用,所以不要這樣做。它已經並將導致難以追蹤的微妙的錯誤。 – 2012-02-28 00:57:03