All IT Courses 50% Off
Python Tutorials

Python time sleep: Examples to add DELAY to your code

Sleep function in Python

Sometimes you need to add delay to your specific code. Python has a built-in Sleep Function for such functionality. The sleep() function is part of the time module. 

Using sleep() function in Python

Let’s take a look at how to use the sleep functions in Python. We will use the current time to check the time difference.

import time
t = time.localtime()
current_time = time.strftime("%H:%M:%S", t)
print(current_time)
print("I am here")
time.sleep(5)
print("I had to wait 5 seconds")
t = time.localtime()
current_time = time.strftime("%H:%M:%S", t)
print(current_time)

The following is the output.

Python sleep function

Delay function execution

Use the time.sleep function in the user-defined function to delay the execution of the python function.

import time
print('Code Execution Started')
def display():
time.sleep(5)
print('I am in function')
   
print('Function Execution Delayed')
display()

Python time sleep: Examples to add DELAY to your code]

Adding delay using Event().wait function

In the threading library there is a function called event.wait() that can be used to add delay in the code.

from threading import Event

print('Code Execution Started')
def display():
print('I am in the function')
Event().wait(5)
display()
Python time sleep: Examples to add DELAY to your code

Using Timer for delay

We can also use timer function to add delay to code.

from threading import Timer
print('Code Execution Started')
def display():
print('I am in the function')
t = Timer(5, display)
t.start()
Python sleep function
Facebook Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Back to top button
Close
Close