Skip to content

Instantly share code, notes, and snippets.

@sebdah
Last active July 18, 2024 14:35
Show Gist options
  • Select an option

  • Save sebdah/832219525541e059aefa to your computer and use it in GitHub Desktop.

Select an option

Save sebdah/832219525541e059aefa to your computer and use it in GitHub Desktop.
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
Copy link
Copy Markdown

perfect
thanks

@rolandovillca
Copy link
Copy Markdown

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

@kambojakhil1991
Copy link
Copy Markdown

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
Copy link
Copy Markdown

thanks

@jennerwein
Copy link
Copy Markdown

Thanks again, clear code, very helpful for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment