Python time.sleep(): How to Pause Execution in Python Scripts
Guide to python time.sleep: syntax, examples, threading behavior, asyncio alternatives, non-blocking techniques, and common pitfalls.
Drake Nguyen
Founder · System Architect
python time.sleep — Overview
The python time.sleep function (time.sleep) is the standard way to pause execution in Python programs for a specified number of seconds. It belongs to the time module and accepts integers or floats, so you can use seconds or fractional seconds (for example, 0.1 to sleep for 100 milliseconds). Keep in mind that time.sleep blocks the current thread while waiting; in single-threaded scripts this will make the whole program wait.
Syntax and basic usage
To use the python sleep function you first import the time module and call time.sleep(seconds). The seconds argument can be a float for sub-second delays:
import time
print("Before sleep")
time.sleep(2) # pause execution python for 2 seconds
print("After sleep")
Examples
Sleep for milliseconds
Use a float to sleep for fractions of a second (useful for rate limiting or dramatic printing):
import time
# sleep for 100 milliseconds
time.sleep(0.1)
python time.sleep example with a loop
Pausing inside a loop is common, but be aware of accumulated delay:
import time
for i in range(5):
print(i)
time.sleep(1) # python pause program for x seconds (1 second each iteration)
python thread sleep example
In multithreading, time.sleep only suspends the thread that called it. Other threads continue to run:
import time
from threading import Thread
class Worker(Thread):
def run(self):
for i in range(3):
print('worker', i)
time.sleep(1)
class Waiter(Thread):
def run(self):
for i in range(2):
print('waiter', i)
time.sleep(2)
Worker().start()
Waiter().start()
When to use time.sleep
- Simulating delays during testing or demos (python time.sleep example for demonstration).
- Adding a pause between network requests to avoid rate limiting (python sleep between requests).
- Simple timers, countdowns, or retry backoff loops.
Limitations and accuracy
time.sleep is subject to OS scheduling and the interpreter, so the actual sleep duration can be slightly longer than requested. For short delays (like 0.001s) accuracy may vary. If precise timing is required, consider measuring elapsed time with time.time() and compensating in a loop.
Alternatives for non-blocking delays
asyncio.sleep
In asynchronous code Netalith not use time.sleep — it will block the event loop. Use asyncio.sleep instead, which suspends only the surrounding coroutine:
import asyncio
async def my_task():
print('start')
await asyncio.sleep(1) # python time.sleep vs asyncio.sleep: non-blocking in async code
print('done')
asyncio.run(my_task())
threading.Timer and schedulers
For callbacks after a delay without blocking a thread, use threading.Timer or scheduling libraries (schedule, APScheduler):
import threading
def delayed():
print('ran after 2 seconds')
t = threading.Timer(2.0, delayed)
t.start() # main thread keeps running
Common issues and debugging
- time.sleep not working python: Often the symptom is that the program appears unresponsive. Confirm whether sleep is running on the main thread—moving it into a background thread or using asyncio can resolve UI freezes.
- Blocking unintentionally: GUI apps and servers should avoid time.sleep on the main thread.
- Using sleep inefficiently in loops: If you need a total delay, sleeping once after the loop may be better than sleeping each iteration.
Best practices
- Prefer asyncio.sleep in async code to keep the event loop responsive.
- Use floats for sub-second delays (python time.sleep float seconds, python sleep 100 milliseconds).
- For recurring or scheduled tasks, use Timer or a scheduling library rather than manual sleeps inside long-running loops.
- If you need to wait for an external condition, prefer polling with a timeout or synchronization primitives (Event, Condition) instead of blind sleeping.
FAQs
Does time.sleep block the thread or process?
time.sleep blocks the calling thread only. In single-threaded programs that has the effect of pausing the whole program; in multithreaded programs other threads will continue to run.
Can time.sleep be interrupted?
Sleep can be interrupted by signals or exceptions (for example KeyboardInterrupt). It does not provide a built-in mechanism to cancel a specific sleep call from another thread.
How to pause for milliseconds?
Pass a float to time.sleep, for example time.sleep(0.05) to pause for 50 milliseconds.
Is time.sleep precise?
time.sleep is suitable for general delays, testing, and rate-limiting, but it is not a high-precision timer. Operating system scheduling and Python overhead affect accuracy.
Conclusion
python time.sleep is a simple, familiar tool to pause execution python programs. Use floats for sub-second delays and remember its blocking nature: choose asyncio.sleep, threading.Timer, or scheduling libraries when you need non-blocking behavior or better responsiveness. When in doubt, prefer explicit synchronization or event-driven designs over blind sleeping.
References: Python time module docs and asyncio documentation provide authoritative details on sleep behavior and async alternatives.