askvity

How do you set a sleep timer in Python?

Published in Python Timeouts 2 mins read

To set a sleep timer in Python, you use the asyncio.sleep() function, specifying the duration in seconds you want the program to pause.

Here's a breakdown:

Using asyncio.sleep()

The asyncio.sleep() function is part of the asyncio library, which is used for writing concurrent code in Python. It allows your program to pause execution for a specified amount of time without blocking other tasks.

  • Import the library:
    import asyncio
  • Call asyncio.sleep():
    • You will need to define an async function, and then use await.
    • Pass the desired wait time in seconds as a parameter. For example, to wait for 2 seconds:
      async def my_function():
          print("Before sleep")
          await asyncio.sleep(2)
          print("After sleep")
  • Run an event loop:
    • You then will need to actually execute your function.
      asyncio.run(my_function())

Practical Insights

  • Timing Accuracy: asyncio.sleep() provides reasonable accuracy for most use cases. However, it might not be suitable for real-time applications with very strict timing requirements.
  • Non-Blocking: Unlike traditional blocking sleep functions, asyncio.sleep() allows other tasks within the same asyncio event loop to proceed while the timer is running.
  • Use in Asynchronous Code: asyncio.sleep() is designed to be used within asynchronous functions (coroutines) and requires an asyncio event loop to function correctly.

Example

Here's a complete example showcasing the use of asyncio.sleep():

import asyncio

async def my_timer_example():
  print("Start of timer example.")
  await asyncio.sleep(1) # pause for 1 second
  print("1 second has passed.")
  await asyncio.sleep(0.5) # pause for 0.5 seconds
  print("1.5 seconds have passed in total.")
  await asyncio.sleep(3) # pause for 3 seconds
  print("4.5 seconds have passed in total.")
  print("End of timer example.")

asyncio.run(my_timer_example())

Table Summary

Function Library Purpose Arguments (Seconds) Usage (async)
asyncio.sleep() asyncio Pauses the execution of an asynchronous function for a given time Floating point number Yes

Related Articles