简体   繁体   中英

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

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 on PYTHON that should stop after for example 1 minute and output the result

i cant search information about this function

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM