Run a class-method every n seconds

怎甘沉沦 提交于 2020-01-03 03:55:07

问题


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?


回答1:


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()


来源:https://stackoverflow.com/questions/26940591/run-a-class-method-every-n-seconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!