How to make Sleep in Python

Learn how to put your Python code to sleep with an example using the time.sleep() function.

Sleep in Python

Python offers a variety of ways to pause or wait for a given amount of time. The most common use for this is to pause a script for a given amount of time before continuing execution. This is useful for programs that need to wait for an external event or for animations that need to be displayed for a given amount of time.

The time.sleep() function is the most commonly used function for pausing a script. It takes one argument, a floating point number, which represents the number of seconds to pause the script. For example, the following code will pause the script for 5 seconds:

import time
time.sleep(5)

The time.sleep() function is useful for waiting for a given amount of time, but it doesn't allow the script to be interrupted by external events. For that, you need to use the threading module. The threading.Event class can be used to create an event that can be used to pause the execution of the script. The event can then be set by other threads or processes to indicate that the script should continue execution.

import threading

def wait_for_event(e):
    """Wait for the event to be set before doing anything"""
    print('wait_for_event starting')
    event_is_set = e.wait()
    print('event set: %s', event_is_set)

e = threading.Event()
t1 = threading.Thread(name='block',
                      target=wait_for_event,
                      args=(e,))
t1.start()

print('Waiting before calling Event.set()')
time.sleep(3)
e.set()
print('Event is set')

In this example, the wait_for_event function will block until the e.wait() call returns. The e.set() call will then unblock the wait_for_event function, allowing it to continue execution. This allows the script to pause for a given amount of time and then be interrupted by an external event.

The time and threading modules offer a variety of ways to pause or wait for a given amount of time. The time.sleep() function is the simplest way to pause a script for a given amount of time, while the threading.Event class can be used to create an event that can be used to pause the execution of the script.

Answers (0)