How to use time.sleep() in a function, while the rest of the script keeps running?

In this tutorial, we will discuss How to use time.sleep() in a function, while the rest of the script keeps running as we know that we can perform this using the time module which could put a certain function on sleep and keep other functions executed as it helps in avoiding certain conditions like a deadlock.

Sleep

Here we will see with some examples of code how we could do so and void such problems.

Sleep Function of Time

Sleep is a function that helps in putting the function on pause when we are required to do so to execute the other function at that time so that we can avoid clash and prevent deadlock

Here is an example showing how we can use the sleep function in a program to continue running other threads when one of the threads is paused.

import threading
import time

def my_ function():
    print(" Start of my_ function")
    time. sleep(5)
    print(" End of my_ function")

print(" Start of script")
t = threading.Thread( target= my_ function)
t.start()
print(" Continuing with the rest of the script")

The above code is written for putting my function at pause for 5 seconds using time. sleep() function However, since it is run in a separate thread, the rest of the script can continue executing while the function is sleeping.

After running the above code we get the output which is given below to understand how exactly it worked for the timing.

Start of script
Start of my_ function
Continuing with the rest of the script
End of my_ function

We can easily predict that the rest of the functions of the program keep on executing at the time of execution but at some time my fiction was paused for 5 seconds which was expected through the code we had written above.

 

To learn more about How to use time.sleep() in a function, while the rest of the script keeps running visit: Sleep function in Python to put the program for at pause for 5 seconds.

To learn more about python programming along with the solutions of the problems faced during coding or understanding the concepts you may visit: How to Counting Distinct values Across Columns Using sqlite3 in Python to enhance your knowledge along with getting new things about python.

To learn more about different other programming languages like MySQL, MongoDB, Java, and C++ solutions and tutorials of concepts visit: beta python programming languages Solutions.

 

Leave a Comment

%d bloggers like this: