Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách tạm dừng (sleep) thread hiện tại trong Python

Dùng time.sleep(seconds) để tạm dừng thread hiện tại trong số giây cho trước. Hỗ trợ cả số thực (phân số giây).

Ví dụ cơ bản

import time

print("Bắt đầu")
time.sleep(2)  # Ngủ 2 giây
print("Sau 2 giây")

# Vòng lặp in mỗi 10 giây
while True:
    print("In mỗi 10 giây")
    time.sleep(10)

Kết quả

Bắt đầu
(Sau 2 giây)
Sau 2 giây
In mỗi 10 giây
(10 giây sau)
In mỗi 10 giây
...

Hỗ trợ phân số giây

time.sleep(0.5)    # 500 ms
time.sleep(0.001)  # 1 ms (độ chính xác phụ thuộc OS)

Lưu ý quan trọng

  • sleep() chỉ block thread hiện tại, không block toàn bộ process (nếu đa luồng).
  • Độ chính xác: Windows ~1-15ms, Linux ~1ms (tùy kernel config).
  • Có thể bị ngắt bởi signal (trên Unix) - ném InterruptedError (Python 3).
  • Để sleep chính xác hơn, xem asyncio.sleep() cho async code.

Ví dụ thực tế: Rate limiting

import time
import requests

urls = ["https://api.example.com/item/{}".format(i) for i in range(100)]

for url in urls:
    response = requests.get(url)
    process(response)
    time.sleep(0.1)  # Nghỉ 100ms giữa các request