Python

Python sleep() Function

1. Introduction

In this article, we will see a simple usage of the python sleep() function. Python is an easy-to-learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.

The Python interpreter is easily extended with new functions and data types implemented in C or C++ (or other languages callable from C). Python is also suitable as an extension language for customizable applications.

2. sleep() function

Python has a module named time that provides several useful functions to handle time-related tasks. One of the popular functions among them is sleep(). The python sleep() function suspends the execution of the current thread for a given number of seconds. Let us see a working example:

import time

x=0
while x<10:
  localtime = time.localtime()  result = time.strftime("%I:%M:%S %p", localtime)
  print('Current time:', result)
  x=x+1
  time.sleep(1)

We first import the time module. We then run a while loop ten times. Every time we print the current time and then make the main thread sleep for a second. When you run the above example you will see a similar output as below:

Fig. 1: First Sleep Example OUtput.
Fig. 1: First Sleep Example OUtput.

3. Multithreading

A computer program is a collection of instructions. A process is the execution of those instructions. You can have multiple threads inside a process. The example we saw above was a single-threaded program – there is only one thread that is doing all the job. Let us create a multi-threaded program

import threading 
import time
  
def firstname():
  for i in range(5):
    time.sleep(.1)
    print("Meraj")
  
def surname(): 
    for i in range(5): 
      time.sleep(.2)
      print("Zia") 

t1 = threading.Thread(target=firstname)  
t2 = threading.Thread(target=surname)  

t1.start()
t2.start()

The above program has two threads t1 and t2. We used the sleep function to suspend the execution of the program. If you run the above program you will see output like the below:

Fig. 2: Second Sleep Example Output.
Fig. 2: Second Sleep Example Output.

4. Conclusion

In this article, we looked at the sleep() function available in Python’s time module. Sometimes, there is a need to halt the flow of the program so that several other executions can take place or simply due to the utility required. sleep() can come in handy in such a situation which provides an accurate and flexible way to halt the flow of code for any period of time.

Mohammad Meraj Zia

Senior Java Developer
Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button