Here’s a little code snippet for running class methods as background threads in Python. The
run() method does some work forever and in this use case you want it to do that in the background (until the main application dies), while the rest of the application continues it’s work.
I’ll walk you through the most important parts.
thread = threading.Thread(target=self.run, args=())- Define which function to execute. Please note that I don’t have any arguments in this example. If you do, just insert them in the
thread.daemon = True- Run the thread in daemon mode. This allows the main application to exit even though the thread is running. It will also (therefore) make it possible to use ctrl+c to terminate the application.
thread.start()- Start the thread execution.