Home  >  Blog  >   Python

Python Sleep Method

Rating: 4
  
 
4934
  1. Share:
Python Articles

Have you ever needed your Python code to wait for something? Most of the time, you want your code to execute as fast as possible. But there are times when you want to delay certain code pieces execution for a small duration, and this task is achieved effortlessly through time.sleep() function in Python. In this article, we’ll discuss the functionality of the Python Sleep() function with detailed examples.

First, let's start by defining what Sleep() is?

If you want to become a Python Certified Specialist, then visit Mindmajix - A Global online training platform: “Python Training”.  This course will help you to achieve excellence in this domain. 

What is Python Sleep()?

In Python, Sleep() function is used to delay program execution. It pauses the execution for a given number of seconds and can take floating-point numbers for more precise sleep time. The suspension time may vary. It is not accurate as it uses the system clock, and the accuracy depends on the operating system. 

The system clock is an Advanced Programmable Interrupt Controller (APIC). It works internally by keeping track of CPU cycles and raising Interrupt Requests (IRQs) at programmable intervals. It interrupts whatever code the processor is currently executing, saves its state, and passes control to a piece of code in the operating system.

Python calls select on Linux (and compatibles) and WaitForSingleObjectEx on Windows. Both of these are normally used for I/O, and when called in a blocking way, OS will put the process on hold until the data is available or the time period is expired. It will resume the process once data is available or the time period has expired.

The Sleep() function is defined both in Python 2 and 3, and it only can pause the current thread and not the whole program. 

Checkout:-Python Operators

Python Time Module

Python has a module called time which provides various useful functions related to time tasks. Sleep() is one of the popular functions among them, that suspends the execution of a current thread for a given number of seconds.

Before using the sleep() function, make sure you import the time module. To do so type:

import time

Syntax:

Following is the syntax for sleep() method -

time.sleep(seconds)

It has only one parameter called seconds, which induces delay for that number of seconds in the code execution. This method doesn't return any value.

Let's see a few examples to understand how this function works.

Python time.sleep() examples:

Example 1) Using sleep() function in Python

import time
print("Welcome to Mindmajix Python Tutorial")
time.sleep(2.4)
print(" Print this message after a wait of 2.4 seconds")

Output:

Welcome to Mindmajix Python Tutorial
Print this message after a wait of 2.4 seconds

Example 2) Create a Simple countdown timer
 
import time
seconds = 5
while seconds > 0:
      print(seconds)
    time.sleep(1)
    seconds = seconds - 1

Output:

5 4 3 2 1

It will print the output with a 1-second delay.

 MindMajix YouTube Channel

Example 3) Print Date and time with a 1-second interval

import time
while True:
  print("DateTime " + time.strftime("%c"))
  time.sleep(1) ## delays for 1 seconds

Output:

DateTime Tue Jan 5 08:40:18 2021

DateTime Tue Jan 5 08:40:19 2021

DateTime Tue Jan 5 08:40:20 2021

DateTime Tue Jan 5 08:40:21 2021

DateTime Tue Jan 5 08:40:22 2021

And continues until stop.

Example 4) Asking user input for wait time

import time
def sleeper():
while True:
        # Get user input
        num = raw_input('How long to wait: ')
 
        # Try to convert it to a float
        try:
            num = float(num)
        except ValueError:
            print('Please enter in a number.n')
            continue
 
        # Run our time.sleep() command,
        # and show the before and after time
        print('Before: %s' % time.ctime())
        time.sleep(num)
        print('After: %sn' % time.ctime())
 
try:
    sleeper()
except KeyboardInterrupt:
    print('nnKeyboard exception received. Exiting.')
    exit()

output :

 
How long to wait: 5

Before: Tue Jan 5 08:47:56 2021

After: Tue Jan 5 08:48:01 2021

Example 5) Adding a delay of the definite interval using Sleep ()

Here, the current time is first displayed and then the execution is paused for 5 seconds using sleep() function.

import time
print ("current time : ",time.ctime())
time.sleep(5)
 print ("after : ",time.ctime())

Output:

Current time: 04:37:56
After: 04:38:01

Example 6) Adding different delay time of python sleep()

In Python, you can add different delay times between the execution of the program depending on the required output.

Example,

import time
for k in [2, 2.5, 3, 3.5]:
  print("I will walk for %s" % k, end='')
  print(" kilometres")
  time.sleep(k)

Output:

I will walk for 2 kilometres
I will sleep for 2.5 kilometres
I will sleep for 3 kilometres
I will sleep for 3.5 kilometres

Using asyncio.sleep

Asynchronous capabilities are added to the Python version 3.4 and higher. Asynchronous programming allows you to run various tasks at once. When a task completes, it will notify the main thread. You need to add async and await to use this function.

Example:

import asyncio

async def main():
print('Hello ...')
    await asyncio.sleep(2)
    print('... World!')

asyncio.run(main())

Python Thread Sleep

The time. Sleep () function plays a vital role in multithreading. For single-threaded programs, the function suspends the execution of thread and process. But for multithreaded programs, the sleep function halts the execution of the current thread only rather than the whole process.

Example:

import time
from threading import Thread


class Student(Thread):
    def run(self):
        for x in range(0, 5):
            print(x)
            time.sleep(1)


class Teacher(Thread):
    def run(self):
        for x in range(10, 25):
            print(x)
            time.sleep(5)


print("Staring Student Thread")
Student().start()
print("Starting Teacher Thread")
Teacher().start()
print("Done")

Output:

Starting Student Thread
0
Starting Teacher Thread 
10
Done 
1
2
3
4
11
5

Using event.wait()

The threading module provides an Event() method. When the event is set, the program will break out of the loop immediately.

The working of this function is shown below:

from threading import Event

print('Start Code Execution')

def display():
    print('Welcome to Mindmajix')


Event().wait(10) 
display()

The code is using Event().wait(10).The number 10 is the number of seconds the code will delay to go to the next line.

 

Frequently Asked Python Interview Questions & Answers

Output:

Start Code Execution
Welcome to Mindmajix

 

time.sleep()

The sleep() function is defined in the time module.

There are two ways to include it in the program

import time
.sleep(5)   ## suspend execution for five seconds
 
from time import sleep
sleep(5)    	## suspend execution for five seconds
 
sleep() can take floating-point numbers as an argument for more precise sleep time.
 
import time
time.sleep(0.100) ## Wait for 100 milliseconds

Example 1: Simple countdown timer

 
import time
 
seconds = 5
while seconds > 0:
      print(seconds)
    time.sleep(1)
    seconds = seconds - 1
 output:

5 4 3 2 1

It will print the output with a 1-second delay.

Example 2: Date and time print with 1-second interval

 
import time
while True:
  print("DateTime " + time.strftime("%c"))
  time.sleep(1) ## delays for 1 seconds
 output: 

DateTime Tue Sep  5 08:40:18 2017

DateTime Tue Sep  5 08:40:19 2017

DateTime Tue Sep  5 08:40:20 2017

DateTime Tue Sep  5 08:40:21 2017

DateTime Tue Sep  5 08:40:22 2017

And continues until stop.

Example 3: Asking user input for wait time

import time
 
def sleeper():
    while True:
        # Get user input
        num = raw_input('How long to wait: ')
 
        # Try to convert it to a float
        try:
            num = float(num)
        except ValueError:
            print('Please enter in a number.n')
            continue
 
        # Run our time.sleep() command,
        # and show the before and after time
        print('Before: %s' % time.ctime())
        time.sleep(num)
        print('After: %sn' % time.ctime())
 
try:
    sleeper()
except KeyboardInterrupt:
    print('nnKeyboard exception received. Exiting.')
    exit()
 output :

How long to wait:  5

Before: Tue Sep  5 08:47:56 2017

After: Tue Sep  5 08:48:01 2017

How It Works:

In Python time.sleep() method blocks thread. If the program is single-threaded, then the process will be also blocked. The substantive part of the sleep operation is wrapped in a Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS block, allowing other threads to continue to execute while the current one sleeps.

If you are interested to learn Python and becoming a Python Expert? Then check out our Python Certification Training Course at your near Cities.

Python Course Chennai, Python Course Bangalore, Python Course Dallas, Python Course Newyork

 These courses are incorporated with Live instructor-led training, Industry Use cases, and hands-on live projects. This training program will make you an expert in Python and help you to achieve your dream job.

 

Conclusion:

In this article, we have discussed the sleep () method in Python with a few code examples of how it works. We hope the information shared is helpful for you to put your code to sleep!

If you have any doubts, let us know in the comment section below, our experts will help you with the best possible solution.

 

Explore Python Sample Resumes! Download & Edit, Get Noticed by Top Employers!Download Now!
Join our newsletter
inbox

Stay updated with our newsletter, packed with Tutorials, Interview Questions, How-to's, Tips & Tricks, Latest Trends & Updates, and more ➤ Straight to your inbox!

Course Schedule
NameDates
Python TrainingApr 30 to May 15View Details
Python TrainingMay 04 to May 19View Details
Python TrainingMay 07 to May 22View Details
Python TrainingMay 11 to May 26View Details
Last updated: 03 Apr 2023
About Author

Anjaneyulu Naini is working as a Content contributor for Mindmajix. He has a great understanding of today’s technology and statistical analysis environment, which includes key aspects such as analysis of variance and software,. He is well aware of various technologies such as Python, Artificial Intelligence, Oracle, Business Intelligence, Altrex, etc. Connect with him on LinkedIn and Twitter.

read more
Recommended Courses

1 / 15