错误重启threading.Timer

时间:2016-10-27 08:39:02

标签: python

我在堆栈上看到并阅读了已回答的问题,但我仍然不知道如何修复它。

我很乐意提供任何帮助。

这是我的代码:

#!/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 个答案:

答案 0 :(得分:1)

您忘了self(因为您的代码在方法下缩进)

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

但这是你应该做的事情,将代码移到类外面并创建一个新对象,然后调用executeTaskFromServer方法

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

你只需要启动一次线程