Idan Moshe Idan Moshe - 1 month ago 16
Python Question

Error restart threading.Timer

I saw and read answered questions here on stack and I'm still don't know how to fix it.

I'll glad for any help.

Here is my code:

#!/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()


And here is the error I'm having:

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


Even when I mark all code in
executeTaskFromServer
and just print 'hi' I'm still having the same problem.

I tried even
class TaskManagmentHandler():
but it didn't solved my problem.

Answer

You forgot self (since your code is indented under the method)

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

But this is what you should do actually, move the code outside the class and create a new object and then call the executeTaskFromServer method

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

You only need to start the thread once

Comments