5

I have a code block that I use for running a piece of code every 30 secs

def hello():
    print "hello, world"
    t = threading.Timer(30.0, hello)
    t.start()

The one below is a method of a class, which I really want to run every 30 secs, but I am having problems with it.

def continousUpdate(self, contractId):    
    print 'hello, world new'
    t = threading.Timer(30.0, self.continousUpdate, [self, contractId],{} )
    t.start()

When I run it, I get the following error

pydev debugger: starting
hello, world new
Exception in thread Thread-4:
Traceback (most recent call last):
  File "C:\Python27\lib\threading.py", line 552, in __bootstrap_inner
   self.run()
  File "C:\Python27\lib\threading.py", line 756, in run
   self.function(*self.args, **self.kwargs)
TypeError: continousUpdate() takes exactly 2 arguments (3 given)

I have also tried

def continousUpdate(self, contractId):    
    print 'hello, world new'
    t = threading.Timer(30.0, self.continousUpdate(contractId))
    t.start()

which somehow behaves as if it ignores the thread, and gives a recursion limit error

2 Answers 2

17

Try this:

t = threading.Timer(30.0, self.continousUpdate, [contractId],{} )

When you read self.continuousUpdate, the method is already bound to the object, even if you don't call it yet. You don't need to pass self again.

The reason the second version "ignores the thread" is that you call the method inside an argument to the Timer call, so it runs (and tries to call itself again) before the Timer ever gets started. That's why threading functions have you pass the function and its arguments separately (so it can call the function itself when it's ready).

Incidentally, you spelled "continuous" wrong.

Sign up to request clarification or add additional context in comments.

Comments

0

Just remove the self parameter. Here is a full working solution:

import threading
class DataCollect():
    def __init__(self):
        pass

    def hello(self):
        print("hello, world")
        t = threading.Timer(5.0, self.hello)
        t.start()
        
dataCollect = DataCollect() 
dataCollect.hello()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.