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.
import threading
import time
class ThreadingExample(object):
""" Threading example class
The run() method will be started and it will run in the background
until the application exits.
"""
def __init__(self, interval=1):
""" Constructor
:type interval: int
:param interval: Check interval, in seconds
"""
self.interval = interval
thread = threading.Thread(target=self.run, args=())
thread.daemon = True # Daemonize thread
thread.start() # Start the execution
def run(self):
""" Method that runs forever """
while True:
# Do something
print('Doing something imporant in the background')
time.sleep(self.interval)
example = ThreadingExample()
time.sleep(3)
print('Checkpoint')
time.sleep(2)
print('Bye')
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 args tuple.
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.
source: http://sebastiandahlgren.se/2014/06/27/running-a-method-as-a-background-thread-in-python/