Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Running a background thread in Python
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')
@tornado80

This comment has been minimized.

Copy link

tornado80 commented Jun 11, 2015

perfect
thanks

@rolandovillca

This comment has been minimized.

Copy link

rolandovillca commented Mar 16, 2016

Thank you, it helps me to understand much better threading.

@kambojakhil1991

This comment has been minimized.

Copy link

kambojakhil1991 commented Feb 12, 2018

If I run it from command Prompt and trying to write it to file in run method in while loop. If its daemon thread it is not entering loop

@Fhwang0926

This comment has been minimized.

Copy link

Fhwang0926 commented Sep 24, 2018

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.