Search code examples
pythonmultithreadingclasstimer

Pass a function that accepts arguments to a class method


I am in my first week in Python. I am trying to create a threaded function that created timers which call a specific function. Here is my code:

import threading
class TimerClass(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.event = threading.Event()
        self.event.set = False
    def run(self, timer_wait, my_fun(print_text)):
        while True:
            my_fun(print_text)
            self.event.wait(timer_wait)

    def stop(self):
        self.event.set = True




def my_fun(text_to_print):
    print(text_to_print)


tmr = TimerClass()
tmr.run(3, my_fun('hello world'))

The result of this code is

def run(self, timer_wait, my_fun(print_text))
                                  ^
SyntaxError: invalid syntax

How can I correct this code?


Solution

  • Just pass the argument separately:

    def run(self, timer_wait, my_fun, print_text): 
        while check_session_live(session):
            my_fun(print_text)
            self.event.wait(timer_wait)
    

    and call it:

    mr.run(3, my_fun, 'hello world')