Calling time.sleep()
is the quickest way to pause Python code for a set number of seconds. For asynchronous code, use asyncio.sleep()
, and for threads or GUIs prefer non-blocking waits so your app stays responsive.
Option 1: Use time.sleep() in synchronous code
Step 1: Import the time module.
import time
Step 2: Pause execution by calling time.sleep(seconds)
.
print("Starting...")
time.sleep(2) # sleep for 2 seconds
print("Done.")
Step 3: Pass a float to sleep for sub-second delays.
time.sleep(0.1) # 100 milliseconds
Step 4: Insert sleeps inside loops to rate‑limit work such as polling or API calls.
for _ in range(5):
print("Tick")
time.sleep(1)
Step 5: Avoid calling time.sleep()
in a GUI’s main thread or inside an async event loop; use the options below to prevent freezing.
Option 2: Use asyncio.sleep() in async functions
Step 1: Define an async function that awaits asyncio.sleep()
instead of blocking.
import asyncio
async def work():
print("Hello ...")
await asyncio.sleep(1)
print("... world!")
Step 2: Run the coroutine with asyncio.run()
so the event loop stays responsive while waiting.
asyncio.run(work())
Step 3: Schedule multiple tasks to wait concurrently for better throughput.
import asyncio
async def step(name, delay):
await asyncio.sleep(delay)
print(f"{name} done")
async def main():
t1 = asyncio.create_task(step("A", 1))
t2 = asyncio.create_task(step("B", 2))
t3 = asyncio.create_task(step("C", 3))
await t1
await t2
await t3
asyncio.run(main())
Option 3: Use Event.wait() for responsive thread delays
With threads, waiting on an event makes shutdown immediate and avoids waiting for a blocking sleep to finish. See event objects in the documentation.
Step 1: Create a threading.Event()
that worker threads can wait on with a timeout.
import threading
import time
stop = threading.Event()
Step 2: In each worker, replace time.sleep()
with stop.wait(timeout)
so the thread can exit immediately when signaled.
def worker():
while not stop.is_set():
print("working...")
# Wait up to 1s, but return early if stop is set
stop.wait(1)
Step 3: Start the worker thread and set the event to stop it cleanly.
t = threading.Thread(target=worker, name="worker-1")
t.start()
time.sleep(3)
stop.set()
t.join()
Option 4: Schedule delays in Tkinter without freezing the UI
In Tkinter, use the widget’s after(ms, callback)
method to run code later without blocking the event loop. Methods are listed in the Tkinter documentation.
Step 1: Create the root window and any UI you need.
import tkinter as tk
root = tk.Tk()
root.geometry("300x150")
Step 2: Schedule a callback with root.after(delay_ms, func)
instead of using time.sleep()
.
def delayed():
print("Ran after 2 seconds")
root.after(2000, delayed)
Step 3: Start the event loop so the UI stays interactive while waiting.
root.mainloop()
Quick tips
time.sleep()
blocks only the current thread; other threads continue running.- Use floats for fractional seconds, for example
time.sleep(0.25)
. - Prefer
asyncio.sleep()
inside async code andEvent.wait()
in threaded services for fast shutdowns. - In GUI apps, schedule work with timers (for example, Tkinter
after
) to prevent frozen windows.
Choose the sleep primitive that matches your runtime: synchronous, async, thread-based, or GUI. You’ll get the delay you need without blocking the parts of your app that must stay responsive.
Member discussion