speendo
speendo

Reputation: 13335

Run a class-method every n seconds

I try to run a class method in Python 3 every n seconds.

I thought that Threading would be a good approach. The question (Run certain code every n seconds) shows how to do that without objects.

I tried to "transfer" this code to OOP like this:

class Test:
    import threading
    def printit():
        print("hello world")
        threading.Timer(5.0, self.printit).start()

test = Test()
test.printit()

>> TypeError: printit() takes no arguments (1 given)

I get this error.

Can you help me doing it right?

Upvotes: 2

Views: 1471

Answers (1)

mdadm
mdadm

Reputation: 1363

Add the argument self into the printit method, and it works for me. Also, import statements should be at the top of the file, not within the class definition.

import threading

class Test:
    def printit(self):
        print("hello world")
        threading.Timer(5.0, self.printit).start()

test = Test()
test.printit()

Upvotes: 3

Related Questions