Skip to content

Instantly share code, notes, and snippets.

@erikseulean
Last active April 13, 2022 22:04
Show Gist options
  • Select an option

  • Save erikseulean/606dc74595b9abfa12355cba0d64d8c3 to your computer and use it in GitHub Desktop.

Select an option

Save erikseulean/606dc74595b9abfa12355cba0d64d8c3 to your computer and use it in GitHub Desktop.
Stop thread after 5 seconds
import threading
import time
def do_something_random_until_stopped(event):
counter = 0
elapsed = time.time()
while not event.isSet():
print(f"I am at {counter}")
counter += 1
time.sleep(0.5)
print(f"I am stopping after {time.time() - elapsed} seconds")
event = threading.Event()
thread = threading.Thread(target=do_something_random_until_stopped, args=(event,))
thread.start()
thread.join(5)
event.set()
% python thread_stop_after_time.py
I am at 0
I am at 1
I am at 2
I am at 3
I am at 4
I am at 5
I am at 6
I am at 7
I am at 8
I am at 9
I am stopping after 5.047975063323975 seconds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment