Search code examples
python-3.xtimewhile-loop

While loop waits without stopping until the time.sleep finishes


I have a while loop in a thread which checks a webstream every 10 minutes.

while not stop_event.is_set():
    time.sleep(600)
    response = requests.get(api_url, headers=headers, params=params)
    if response.status_code==200:
        print("UPDATED")
    else:
        print("NOT UPDATED")

But if the not stop_event.is_set() changed to False before 10 minutes, Still the while loop waits 10 minutes and executes the rest of the code and then exits

    response = requests.get(api_url, headers=headers, params=params)
    if response.status_code==200:
        print("UPDATED")
    else:
        print("NOT UPDATED")

I want to quit immediately as the not stop_event.is_set() changed to False without witing time.sleep(600) to finish

Thanks in advance


Solution

  • Instead of time.sleep, which is blocking, you could use threading.Event.wait which will return immediately if the internal flag is set:

    while not stop_event.is_set():
        if stop_event.wait(600):
            break # or use "return" if you want the entire function to end
        response = requests.get(api_url, headers=headers, params=params)
        if response.status_code == 200:
            print("UPDATED")
        else:
            print("NOT UPDATED")
    

    A reproducible example:

    import time
    import threading
    
    
    def run_in_thread(stop_event):
        while not stop_event.is_set():
            if stop_event.wait(5):
                print(f"{time.strftime('%H:%M:%S', time.localtime())}: Stopped.")
                return
            print(f"{time.strftime('%H:%M:%S', time.localtime())}: Running.")
    
    
    if __name__ == '__main__':
        stop_event = threading.Event()
        t = threading.Thread(target=run_in_thread, args=(stop_event,))
        t.start()
        time.sleep(16)
        stop_event.set()