Skip to content

Commit 4ef5468

Browse files
lpozobzaczynski
andauthored
Sample code for: Python sleep(): How to Add Time Delays to Your Code (#769)
* Sample code for: Python sleep(): How to Add Time Delays to Your Code * Final QA --------- Co-authored-by: Bartosz Zaczyński <bartosz.zaczynski@gmail.com>
1 parent cb17b1e commit 4ef5468

12 files changed

Lines changed: 199 additions & 0 deletions

python-sleep/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Python sleep(): How to Add Time Delays to Your Code
2+
3+
This folder provides the code examples for the Real Python tutorial [Python sleep(): How to Add Time Delays to Your Code](https://realpython.com/python-sleep/)

python-sleep/coffee.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import time
2+
3+
print("Brewing coffee...")
4+
print("This would take like 3 secs...")
5+
time.sleep(3)
6+
print("Done! Your coffee is ready!")

python-sleep/download.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import urllib.error
2+
import urllib.request
3+
4+
from utils import retry
5+
6+
7+
@retry(delay=3)
8+
def download_file(url):
9+
try:
10+
response = urllib.request.urlopen(url)
11+
print(f"Downloaded {url} ({response.length} bytes)")
12+
except urllib.error.URLError as e:
13+
print(f"Download failed: {e.reason}")
14+
raise
15+
16+
17+
if __name__ == "__main__":
18+
download_file("http://www.example.com/data.csv")

python-sleep/frozen_app.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import time
2+
import tkinter
3+
4+
DELAY = 3 # Sleep for 3 seconds
5+
6+
7+
def on_click():
8+
time.sleep(DELAY)
9+
print("Done!")
10+
11+
12+
root = tkinter.Tk()
13+
root.geometry("400x400")
14+
button = tkinter.Button(text="Click me!", command=on_click)
15+
button.pack()
16+
17+
root.mainloop()

python-sleep/hello_async.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import asyncio
2+
3+
4+
async def main():
5+
print("Hello ...")
6+
await asyncio.sleep(1)
7+
print("... World!")
8+
9+
10+
if __name__ == "__main__":
11+
asyncio.run(main())

python-sleep/rate_limited.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import asyncio
2+
3+
import aiohttp
4+
5+
RATE_LIMIT_DELAY = 1 # Seconds between API requests
6+
7+
8+
async def fetch_page(session, url):
9+
async with session.get(url) as response:
10+
print(f"{url} ({response.status})")
11+
await asyncio.sleep(RATE_LIMIT_DELAY)
12+
13+
14+
async def main():
15+
urls = [
16+
"https://httpbin.org/get",
17+
"https://httpbin.org/ip",
18+
"https://httpbin.org/headers",
19+
]
20+
async with aiohttp.ClientSession() as session:
21+
for url in urls:
22+
await fetch_page(session, url)
23+
24+
25+
if __name__ == "__main__":
26+
asyncio.run(main())

python-sleep/requirements.txt

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
aiohappyeyeballs==2.6.2
2+
aiohttp==3.13.5
3+
aiosignal==1.4.0
4+
attrs==26.1.0
5+
frozenlist==1.8.0
6+
idna==3.15
7+
multidict==6.7.1
8+
propcache==0.5.2
9+
yarl==1.24.2

python-sleep/responsive_app.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import tkinter
2+
3+
DELAY = 3000 # The after() method takes milliseconds (3000 ms = 3 seconds)
4+
5+
6+
def on_click():
7+
root.after(DELAY, lambda: print("Done!"))
8+
9+
10+
root = tkinter.Tk()
11+
root.geometry("400x400")
12+
button = tkinter.Button(text="Click me!", command=on_click)
13+
button.pack()
14+
15+
root.mainloop()

python-sleep/sleep_use.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import time
2+
3+
# Sleep for 3 seconds
4+
time.sleep(3)
5+
6+
# Pass fractional seconds for shorter delays
7+
time.sleep(0.5) # Wait 500 milliseconds
8+
time.sleep(0.001) # Wait 1 millisecond
9+
time.sleep(1.5) # Wait 1.5 seconds
10+
time.sleep(60) # Wait 1 minute

python-sleep/thread_monitor.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import logging
2+
import threading
3+
4+
WORKER_INTERVAL = 1 # Seconds between worker check-ins
5+
MAIN_INTERVAL = 0.75 # Seconds between main thread check-ins
6+
7+
8+
def worker(event):
9+
while not event.is_set():
10+
logging.debug("Worker thread checking in")
11+
event.wait(WORKER_INTERVAL)
12+
13+
14+
def main():
15+
logging.basicConfig(
16+
level=logging.DEBUG,
17+
format="{relativeCreated:>6,.0f} ms | {threadName:<18} | {message}",
18+
style="{",
19+
)
20+
event = threading.Event()
21+
22+
thread_one = threading.Thread(target=worker, args=(event,))
23+
thread_two = threading.Thread(target=worker, args=(event,))
24+
thread_one.start()
25+
thread_two.start()
26+
27+
while not event.is_set():
28+
try:
29+
logging.debug("Main thread checking in")
30+
event.wait(MAIN_INTERVAL)
31+
except KeyboardInterrupt:
32+
event.set()
33+
break
34+
35+
36+
if __name__ == "__main__":
37+
main()

0 commit comments

Comments
 (0)