Python time.sleep indefinitely

Question:

In Python’s time module, there is a sleep() function, where you can make Python wait x seconds before resuming the program. Is there a way to do this indefinitely until a condition is met? For example:

while True:
    time.sleep()
    if x:
        break

time.unsleep()

I am trying to make a pause function for my PyGame program. Any help is appreciated.

Asked By: vkumar

||

Answers:

Something like this:

while not x: time.sleep(0.1)

will wait until x is true, sleeping a tenth of a second between checks. This is usually short enough for your script to seem to react instantly (in human terms) when x becomes true. You could use 0.01 instead if this is not quick enough. In my experience, today’s computers are fast enough that checking a simple condition even every hundredth of a second doesn’t really make a dent in CPU usage.

Of course, x should be something that can actually change, e.g. a function call.

Answered By: kindall

Your code in the question implies that you want some other thread to resume your program. In that case you could use resumed = threading.Event(). You could create it in one thread and pass it into another:

while not resumed.wait(): # wait until resumed
    "continue waiting"

Call resumed.set() to resume this code immediately.

I am trying to make a pause function for my PyGame program. Any help is appreciated.

Use pygame.time. Typically, you have the main loop where you update the state of the game and at the end of the loop you call clock.tick(60) # 60 fps. It is enough to use paused flag in this case, to skip the updating.

Answered By: jfs

You could spin off a thread as follows:

import sys    
import time
from threading import Thread

prepare_to_stop = 0

def in_background_thread():
    while not prepare_to_stop:
        # Program code here
        print(prepare_to_stop)
        time.sleep(0.1)

try:
    th = Thread(target=in_background_thread)
    th.start()
    print("nProgram will shut down after current operation is complete.n")
    time.sleep(10**8)
except KeyboardInterrupt:
    prepare_to_stop = 1

print("Program shutting down...")
Answered By: Joshua Fox
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.