Last active
April 13, 2022 22:04
-
-
Save erikseulean/606dc74595b9abfa12355cba0d64d8c3 to your computer and use it in GitHub Desktop.
Stop thread after 5 seconds
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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