Search code examples
pythonwhile-looptimeout

Python While reach timeout


I am running a Python script on a Windows machine that needs to exit from the while loop when timeout is reached or flag is True:

import time
start_time = time.time()
flag = False
timeout = 5

while time.time() < timeout + start_time:
    # DO something
    flag = True
    break

if flag is False:
   print(f"Timeout reached {timeout}")

With the current code, the timeout or the flag are not hit. Any hints of what it is wrong?


Solution

  • I am going to post the solution that I have found and worked for me as in the #DO SOMETHING section I had some blocks of code that were using some libraries that were in conflict with multithreading public library:

    import time
    
    MAX_TIMEOUT = 5
    
    start_time = time.time()
    while True:
        time_delta = time.time() - start_time
        while time_delta <= MAX_TIMEOUT:
            # DO SOMETHING
            finished = True
            break
            if finished:
               break
            if time_delta > MAX_TIMEOUT:
                print("Timeout reached.")
                break