Python: can the time library do task: the loop should stop when a certain time passes?

Question:

Can the time library help with the task: the loop should stop when a certain time passes? I’m going to write a light game program in Python that should stop after for example 1 minute and output the result.

I can’t find information about this function.

Asked By: Doggen

||

Answers:

The straightforward solution is to run a while-loop with a time-checking boolean expression:

from datetime import datetime, timedelta

end_time = datetime.now() + timedelta(minutes=1)

while end_time >= datetime.now():
    print("Your code should be here")

Another more sophisticated approach is to run the program in a separate thread. The thread checks for an event flag to be set in a while loop condition:

import threading
import time


def main_program(stop_event):
    while not stop_event.is_set():
        print("Your code should be here")


stop_event = threading.Event()
th_main_program = threading.Thread(target=main_program, args=(stop_event,))
th_main_program.start()
time.sleep(60)
stop_event.set()

In the approaches shown above the program execution finishes gracefully but an iteration within the while-loop has to be finished to check the boolean expression. This means the program doesn’t exit immediately once the timeout is reached.

To make the main program exit right away once the timeout is reached, we can use daemon thread. Please note that daemon threads are abruptly stopped at shutdown. Their resources may not be released properly:

import threading
import time


def main_program():
    while True:
        print("Your code should be here")


th_main_program = threading.Thread(target=main_program, daemon=True)
th_main_program.start()
time.sleep(60)
Answered By: Ivan

You need to take time at the start and break your loop when the difference between current time and time at the start is more than you want.

import time

start_time = time.time()

while True:
    current_time = time.time()
    if current_time - start_time > 60: #time in seconds
        break
    #your code

You can also add time.sleep(0.01) to the loop to limit your fps.

Answered By: Nejc
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.