Explain Codes LogoExplain Codes Logo

How do I make a time delay?

python
time-delay
asyncio
selenium
Anton ShumikhinbyAnton Shumikhin·Aug 7, 2024
TLDR

Pause your Python script with the time.sleep() command specifying the seconds of delay as shown below:

import time time.sleep(5) # Nap time, wakes up in 5 seconds.

Substitute 5 with any float or integer to set the duration of the pause.

Pimp My Code: Customize your delay

Call directly

No need for time.sleep(), call sleep() directly and save typing:

from time import sleep # Quick break, be right back… sleep(2.5)

Loop the loop

Squeeze sleep() into your loops for timely pauses:

for _ in range(10): solve_world_hunger() sleep(60) # Takes a 1-minute power nap

Finer than fine

Sub-second delays? We've got you covered:

sleep(0.5) # Gone in the blink of an eye

Just-In-Time Pausing

Introduce rest stoppages at strategic junctures like after network requests or during busy loops.

Advanced convenience

Threads, pools and executors

You can line up concurrent tasks using ThreadPoolExecutor and ProcessPoolExecutor to execute tasks in the background:

from concurrent.futures import ThreadPoolExecutor import time def background_task(): time.sleep(3) print("Task done, what’s next boss?") with ThreadPoolExecutor() as executor: future = executor.submit(background_task) # Can grab a coffee while the task is cooking…

Asynchronous dot-sleep

When napping in an async-function, replace time.sleep() with asyncio.sleep():

import asyncio async def async_slumber(): await asyncio.sleep(1) print("Slept like a log, let’s roll!") # Remember to tuck it into an async function or an event loop

Selenium’s patience virtues

Instead of generic waits, use targeted waiting with Selenium:

from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC wait = WebDriverWait(driver, 10) element = wait.until(EC.presence_of_element_located((By.ID, 'element_id'))) # Good things come to those who wait

Tkinter’s time-out trick

In Tkinter, use the .after command to keep the UI responsive while pausing:

import tkinter as tk def update_ui(): # UI update code here print("UI updated, feast your eyes!") root = tk.Tk() root.after(2000, update_ui) # Does a quick round of hide-and-seek for 2 seconds

When to avoid time.sleep()

While time.sleep() is pretty cool, here’s when you might not want to use it:

  • Pause-approach inasks – For Tkinter, use root.after() as time.sleep() takes the whole event loop with it.
  • Web Automations – Selenium’s wait.until() provides smarter waits.
  • Async-codeasyncio.sleep() is the way to go.
  • Non-blocking delaysthreading.Timer or sched module can be effective.