Search code examples
pythonloopspython-multithreading

Threading - close while loop


I have a while loop:

while True:
    x = threading.Timer(3, something)
    x.start()
    # whatever
    x.cancel()

I want something to be a function or something to close the loop automatically if the timer runs out.


Solution

  • Since threading.Timer creates a thread, you could do something like this to generate a fake KeyboardInterrupt to interrupt the loop:

    from time import sleep
    import threading
    import _thread as thread  # Low-level threading API
    
    
    def something():
        thread.interrupt_main()  # Raises KeyboardInterrupt.
    
    try:
        while True:
            print('loop iteration started')
            x = threading.Timer(3, something)
            x.start()
            sleep(4)
            x.cancel()
            print('loop iteration completed')
    except KeyboardInterrupt:
        print('timeout occurred - loop closed')
    
    print('-fini-')