- Aliases
- and operator
- Booleans
- Classes
- Code blocks
- Comments
- Conditional statements
- Console
- datetime module
- Dictionaries
- enum
- enumerate() function
- Equality operator
- False
- Floats
- For loops
- Formatted strings
- Functions
- Greater than operator
- Greater than or equal to operator
- If statement
- in operator
- Indices
- Inequality operator
- Integers
- Less than operator
- Less than or equal to operator
- List append() method
- List insert() method
- List pop() method
- List sort() method
- Lists
- map() function
- Match statement
- Modules
- None
- not operator
- or operator
- Parameters
- print() function
- range() function
- Regular expressions
- requests Library
- return statement
- round() function
- Sets
- String join() method
- String replace() method
- String split() method
- Strings
- time.sleep() function
- True
- try...except statement
- Tuples
- Variables
- While loops
PYTHON
Python time.sleep()
: Pausing Code Execution in Python
The Python time.sleep()
function allows you to halt the execution of a program for a specified time. You can use time.sleep()
to delay actions in your program, create timed pauses, or control the execution flow.
How to Use time.sleep()
in Python
The time.sleep()
function is part of Python's time
module. To use it, you first need to import the module. The function takes a single argument representing the number of seconds to delay the execution.
To use the time.sleep()
function, you need to import Python's time
module. The function takes a single argument representing the number of seconds to halt the execution.
import time
# Pause execution for 2 seconds
time.sleep(2)
When to Use Time Sleep in Python
Rate-Limiting API Requests
When interacting with APIs, you might need to limit the rate of requests to avoid being blocked. You can use time.sleep()
to introduce a delay between API calls, ensuring you don't exceed the rate limit.
import time
import requests
url = '<https://api.example.com/data>'
for _ in range(3):
response = requests.get(url)
print(response.status_code)
time.sleep(2) # Delay for 2 seconds between API requests
In this example, time.sleep()
prevents the program from making too many requests too quickly.
Adding Sleeping Time in Python
You can use time.sleep()
to add delays to scripts for automating tasks. Using such delays, you can mimic human behavior, prevent task overload, or wait for a resource to become available.
import time
def simulate_task():
print("Starting task...")
time.sleep(3) # Simulate a delay of 3 seconds
print("Task completed!")
simulate_task()
In this example, time.sleep()
adds a 3-second delay to simulate a task taking time to complete.
Delaying Program Startup
You can also use time.sleep()
to introduce a startup delay, e.g. if your program needs to wait for a different service to start.
import time
print("Waiting for 5 seconds before starting the program...")
time.sleep(5)
print("Program started!")
This example adds a 5-second delay before continuing the program’s execution.
Examples of Using time.sleep()
in Python
Web Scraping with Controlled Requests
Scripts to scrape web pages might use time.sleep()
to avoid overwhelming the server or triggering anti-bot mechanisms.
import time
import requests
urls = ['<https://example.com/page1>', '<https://example.com/page2>', '<https://example.com/page3>']
for url in urls:
response = requests.get(url)
print(f"Fetched {url} with status {response.status_code}")
time.sleep(1) # Delay for 1 second between each request
Countdown Timer in a User Interface
A countdown timer can be implemented using time.sleep()
. This might be useful in a command-line interface or any scenario where you want to display a countdown.
A countdown timer app might use time.sleep()
, pausing the program for a second between each decrement.
import time
def countdown(seconds):
while seconds:
print(f"Time left: {seconds} seconds")
time.sleep(1)
seconds -= 1
print("Time's up!")
countdown(5)
In this example, the program counts from 5 to 0, pausing for 1 second between each number.
Server Monitoring Program
A server monitoring program needs to check the status of several servers every few minutes to detect downtime. Using time.sleep()
and threading, the program can run checks on multiple servers in parallel without overwhelming the system.
import threading
import time
import requests
# Function to monitor server status periodically
def monitor_server(server_url, check_interval):
while True:
try:
response = requests.get(server_url)
print(f"{server_url} is {'up' if response.status_code == 200 else 'down'}")
except requests.ConnectionError:
print(f"Failed to connect to {server_url}")
time.sleep(check_interval)
# List of servers to monitor
servers = [
("https://server1.com", 10),
("https://server2.com", 15),
("https://server3.com", 20)
]
# Create and start threads for each server
for url, interval in servers:
threading.Thread(target=monitor_server, args=(url, interval)).start()
Learn More About Python time.sleep()
Python Sleep Function for Fractional Seconds
The time.sleep()
function allows you to specify sleep intervals down to fractions of a second. Using floating-point numbers with time.sleep()
gives you fine-grained control over timing.
import time
# Sleep for 0.5 seconds (500 milliseconds)
time.sleep(0.5)
print("Half a second delay")
Limitations of Python Time Sleep
While time.sleep()
helps introduce delays, it's important to remember that the function blocks the entire program from executing. During the sleep period, no other code will execute. To maintain responsiveness, consider using asynchronous programming with asyncio.sleep()
.
import asyncio
async def task():
print("Task started")
await asyncio.sleep(2) # Sleep for 2 seconds without blocking the entire program
print("Task completed")
# Running the asynchronous task
asyncio.run(task())
Asynchronous sleep()
is better suited for concurrent programming and non-blocking delays.
Threading with time.sleep()
You can use time.sleep()
to pause multi-threaded applications within individual threads without affecting other threads running in parallel.
import time
import threading
def task():
print("Task started")
time.sleep(3)
print("Task completed after 3 seconds")
thread = threading.Thread(target=task)
thread.start()
# Main program continues running while the task is sleeping
print("Main program is running...")
Using time.sleep()
in a separate thread keeps your main program responsive while introducing a delay in background tasks.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.