2016-10-27 67 views
0

我看到和閱讀堆棧上的回答問題,我仍然不知道如何解決它。錯誤重新啓動threading.Timer

我很樂意爲您提供幫助。

這裏是我的代碼:

#!/usr/local/bin/python 

import threading 

class TaskManagmentHandler: 
    # Handle tasks from server 

    MINUTES_TO_FIRST_TASK = 5 
    MINUTES_TO_NORMAL_TASK = 20 
    MINUTES_TO_FAILED_TASK = 20 

    global currentAwaitingTime 
    currentAwaitingTime = MINUTES_TO_FIRST_TASK 

    def executeTaskFromServer(self): 
     print ("hi!") 

     self.currentAwaitingTime = self.MINUTES_TO_NORMAL_TASK 

     taskThread = threading.Timer(self.currentAwaitingTime, self.executeTaskFromServer()) 
     taskThread.start() 

    # start normal task after 5 minutes 
    # start cycled task every 20 minutes (task call itself after 20 minutes) 

    if __name__ == "__main__": 
     print ("hello!") 
     taskThread = threading.Timer(currentAwaitingTime, executeTaskFromServer) 
     taskThread.start() 

這裏是我遇到的錯誤:

hello! 
Exception in thread Thread-1: 
Traceback (most recent call last): 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 810, in __bootstrap_inner 
    self.run() 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 1082, in run 
    self.function(*self.args, **self.kwargs) 
TypeError: executeTaskFromServer() takes exactly 1 argument (0 given) 


Process finished with exit code 0 

即使我標記所有代碼executeTaskFromServer,只是打印「HI」,我仍然有同樣的問題。我試過class TaskManagmentHandler():,但它沒有解決我的問題。

回答

1

你忘self(因爲你的代碼的方法下縮進)

taskThread = threading.Timer(currentAwaitingTime, self.executeTaskFromServer) 

但是這是你應該真正做什麼,移動代碼的類以外,並創建一個新的對象,然後調用executeTaskFromServer方法

if __name__ == "__main__": 
    print ("hello!") 
    task_mgr = TaskManagmentHandler() 
    task_mgr.executeTaskFromServer() 

你只需要啓動線程一次