How to Sleep in Python (time.sleep and More)

Here’s how to sleep in Python: import time and call time.sleep(seconds). It pauses the current thread for that many seconds, and fractions work too:

import time
time.sleep(2)      # 2 seconds
time.sleep(0.5)    # half a second

I timed every pause with time.perf_counter() on Python 3.12.5, so you can see how accurate the sleeps really are.

We’ll measure time.sleep(), build a countdown, retry a flaky call with backoff, keep a loop on schedule, sleep without blocking using asyncio, and stop a sleeping thread early.

How to sleep in Python with time.sleep()

The argument is in seconds and can be a float. The actual pause is very close to what you ask for, usually a tiny bit longer:

import time

for seconds in [1, 0.5, 0.25, 0.01]:
    start = time.perf_counter()
    time.sleep(seconds)                    # pause this thread
    print(f"asked for {seconds:>5} s, slept {time.perf_counter() - start:.4f} s")

print("Launching in", end=" ", flush=True)
for n in range(3, 0, -1):
    print(n, end="... ", flush=True)
    time.sleep(1)
print("go!")

Output:

asked for     1 s, slept 1.0003 s
asked for   0.5 s, slept 0.5007 s
asked for  0.25 s, slept 0.2504 s
asked for  0.01 s, slept 0.0105 s
Launching in 3... 2... 1... go!
Command Prompt output of Python time.sleep timings for 1, 0.5, 0.25 and 0.01 seconds plus a 3-second countdown
Each sleep lands within a few thousandths of a second of the target, and the countdown ticks once a second.

flush=True makes each number appear immediately instead of waiting for the line to finish. For milliseconds, divide by 1,000: time.sleep(250 / 1000). To clear the screen between updates, see clear screen in Python.

Retry with a sleep and exponential backoff

A classic use is waiting before retrying a failed network call. Doubling the delay each time is polite to the server and gives problems time to clear:

import random
import time

random.seed(7)

def fetch_price():
    if random.random() < 0.6:              # pretend the API is flaky
        raise ConnectionError("store API timed out")
    return 19.99

delay = 0.5
for attempt in range(1, 6):
    try:
        print(f"attempt {attempt}: price ${fetch_price():.2f}")
        break
    except ConnectionError as err:
        print(f"attempt {attempt}: {err}; retrying in {delay:.1f} s")
        time.sleep(delay)
        delay *= 2                          # exponential backoff

Output:

attempt 1: store API timed out; retrying in 0.5 s
attempt 2: store API timed out; retrying in 1.0 s
attempt 3: price $19.99
Command Prompt output of a Python retry loop using time.sleep with exponential backoff until a price is fetched
Two failures with growing waits, then success on the third attempt.

Real code should cap the delay and the number of attempts. For running external commands with timeouts, see run shell commands in Python.

Keep a loop on schedule (avoid drift)

sleep(1) after some work doesn’t give you one tick per second, because the work time adds up. Sleep until the next scheduled tick instead:

import time

def work():
    time.sleep(0.15)                        # each "job" takes 0.15 s

start = time.monotonic()
for i in range(5):
    work()
    time.sleep(1)                           # naive: the job time adds up
print(f"naive loop:     {time.monotonic() - start:.2f} s for 5 ticks")

start = next_tick = time.monotonic()
for i in range(5):
    work()
    next_tick += 1
    time.sleep(max(0, next_tick - time.monotonic()))   # sleep only what's left
print(f"scheduled loop: {time.monotonic() - start:.2f} s for 5 ticks")

Output:

naive loop:     5.77 s for 5 ticks
scheduled loop: 5.00 s for 5 ticks
Command Prompt output comparing a drifting Python sleep loop with a schedule based on time.monotonic
The naive loop took noticeably longer than 5 seconds; the scheduled one stayed on time.

Use time.monotonic() for scheduling, not time.time(). It never jumps when the system clock changes.

asyncio.sleep vs time.sleep

time.sleep() blocks the whole thread. Inside async code, await asyncio.sleep() lets other tasks run while one waits:

import asyncio
import time

async def check_store(city, seconds):
    await asyncio.sleep(seconds)            # doesn't block the other tasks
    return f"{city} ok"

async def main():
    start = time.perf_counter()
    results = await asyncio.gather(check_store("Austin", 1), check_store("Denver", 1), check_store("Miami", 1))
    print(results, f"in {time.perf_counter() - start:.2f} s with asyncio.sleep")

asyncio.run(main())

start = time.perf_counter()
for city in ["Austin", "Denver", "Miami"]:
    time.sleep(1)
print(f"three time.sleep(1) calls in a row: {time.perf_counter() - start:.2f} s")

Output:

['Austin ok', 'Denver ok', 'Miami ok'] in 1.01 s with asyncio.sleep
three time.sleep(1) calls in a row: 3.00 s
Command Prompt output showing three Python asyncio.sleep calls finishing in about 1 second versus three time.sleep calls taking 3 seconds
Three 1-second async waits overlap and finish in about a second; three blocking sleeps take three.

Never call time.sleep() inside an async def; it freezes every task on the event loop.

Stop a sleep early with threading.Event

A background thread stuck in time.sleep(60) can’t be told to quit. Event.wait(timeout) sleeps the same way but wakes up the moment the event is set:

import threading
import time

stop = threading.Event()

def reporter():
    while not stop.wait(timeout=1):         # sleeps up to 1 s, wakes early if stop is set
        print("  reporting sales...")
    print("  reporter stopped right away")

t = threading.Thread(target=reporter)
start = time.perf_counter()
t.start()
time.sleep(2.5)
stop.set()
t.join()
print(f"finished after {time.perf_counter() - start:.2f} s")

Output:

  reporting sales...
  reporting sales...
  reporter stopped right away
finished after 2.50 s

This is my go-to pattern for background workers that need a clean shutdown. More loop patterns are in infinite loops in Python.

Which sleep should you use?

SituationUse
Simple pause in a scripttime.sleep(seconds)
Inside async codeawait asyncio.sleep(seconds)
Background thread you need to stopevent.wait(timeout)
Steady repeating timerSleep until the next time.monotonic() tick
GUI apps (tkinter, PyQt)The toolkit’s timer, such as after() or QTimer

More guides on loops and timing:

Frequently asked questions

How do I make Python wait for a few seconds?

Use import time and then time.sleep(3) to wait three seconds.

How do I sleep for milliseconds in Python?

Pass a fraction of a second: time.sleep(0.25) waits 250 milliseconds.

Does time.sleep block other code?

It blocks the current thread only. Other threads keep running, but async tasks on the same loop freeze.

How accurate is time.sleep?

Usually within a millisecond or two on modern systems, and never shorter than requested except when interrupted.

How do I stop a sleeping thread?

Use threading.Event().wait(timeout) instead of sleep, and call set() to wake it.

Where is time.sleep documented?

See time.sleep in the Python docs.