- Python’s time.sleep() – Pause, Stop, Wait or Sleep your Python Code
- Python’s time.sleep() – Pause, Stop, Wait or Sleep your Python Code
- The time.sleep() function
- time.sleep() Arguments
- Using Python’s time.sleep()
- Advanced syntax of the sleep() function
- The Accuracy of time.sleep()
- Using Decorators To Add time.sleep() Command
- Using Threads To Add time.sleep() Command
- Python time.sleep(): Add Delay to Your Code (Example)
- time.sleep() Syntax
- Parameters
- Example: Using sleep() function in Python
- How to delay the execution of function using sleep()?
- What are the different ways to add a delay in Python Script?
- Using sleep() function
- Using asyncio.sleep function available from (Python 3.4 or higher)
- Using Event().wait
- Using Timer
- Summary
Python’s time.sleep() – Pause, Stop, Wait or Sleep your Python Code
Suppose you are developing a user interface, and you support it with your code. Your user is uploading a document, and your code needs to wait for the time the file is being uploaded. Also, when you visit a complex having automated doors, you must have noticed that while you are entering the complex, the door stands still. Only when you have entered the complex, the door closes automatically. What is causing the delay in both situations?
Codes support both systems discussed above. It is the time delay function of programming languages that is causing the required time delay. We can also add time delays in our Python codes. The time module of Python allows us to establish delay commands between two statements. There are numerous ways to add a time delay and, in this article, we will discuss each method step-by-step.
Python’s time.sleep() – Pause, Stop, Wait or Sleep your Python Code
Python’s time module has a handy function called sleep() . Essentially, as the name implies, it pauses your Python program. The time.sleep() command is the equivalent to the Bash shell’s sleep command. Almost all programming languages have this feature.
The time.sleep() function
While using this function, we can specify the delay, and the compiler will execute the fixed time delay. The syntax of this function is as follows:
time.sleep() Arguments
- secs — The number of seconds the Python program should pause execution. This argument should be either an int or float .
Using Python’s time.sleep()
Here’s a quick, simple example of the syntax:
Here we have instructed the system to wait for five seconds through the first command and then wait for three hundred milliseconds, which equals 0.3 seconds. You can note here that we have written the value of the time delay inside the bracket based on the syntax.
Now let us consider another example to execute time delay.
Here we have taken a variable ‘a’ whose value we have stored as five. Now we are printing the value ‘a’ and then again printing an increased value of ‘a’. However, there is a time delay between the execution of both statements. And, we have specified that using the time.sleep() function. You must have observed that we have also imported the time module at the beginning of the code.
Now let’s see what the output is:
Here we can see that only the first command is executed. Now the output after five seconds:
Now, after a delay of five seconds, the second statement is also executed.
Advanced syntax of the sleep() function
Here’s a more advanced example. It takes user input and asks you how long you want to sleep() . It also proves how it works by printing out the timestamp before and after the time.sleep() call. Note that Python 2.x uses the raw_input() function to get user input, whereas Python 3.x uses the input() function. Now let us see the input syntax:
The code given above asks the user how long to wait. We have mentioned the command for this output in the sleeper() function. Then, the code prints the computer time at the beginning of the execution of code and after the implementation of code. This way, we get to see the actual functioning of the delay function. Now let’s see the output:
The system asks for our input, i.e., how long we want the system to wait. Let’s enter 5 seconds and observe the final output.
We can see that the starting computer time(“Before”) and ending computer time(“After”) have a time difference of five seconds.
The Accuracy of time.sleep()
The time.sleep() function uses the underlying operating system’s sleep() function. Ultimately there are limitations of this function. For example, on a standard Windows installation, the smallest interval you may delay is 10 — 13 milliseconds. The Linux kernels tend to have a higher tick rate, where the intervals are generally closer to 1 millisecond. Note that in Linux, you can install the RT_PREEMPT patch set, which allows you to have a semi-realtime kernel. Using a real-time kernel will further increase the accuracy of the time.sleep() function. However, unless you want to sleep for a brief period, you can generally ignore this information.
Using Decorators To Add time.sleep() Command
Decorators are used for creating simple syntax for calling higher-order functions. When can we use decorators? Suppose we have to test a function again, or the user has to download a file again, or you have to check the status of an interface after a specific time interval. You require a time delay between the first attempt and the second attempt. Thus, you can use decorators in cases where you need to check repeatedly and require a time delay.
Let’s consider an example using decorators. In this program, we will calculate the amount of time taken for the execution of the function.
Here time_calc() is the decorator function extending and containing the other functions, thus providing a simple syntax. Let’s see what we get as the output.
Using Threads To Add time.sleep() Command
Multiple-threading in Python is equivalent to running several programs simultaneously. When multi-threading is combined with the time module, we can solve complex problems quickly. Multi-threading functions are available from the threading module.
Let’s print the alphabet song using multi-threading and time delay.
Here one thread is being used to print the individual alphabets. There is a time delay of 0.5 seconds as well. When you run the program, you will see that each line of the alphabet song is printed after a delay of 0.5 seconds. Let’s see what the output is:
Python time.sleep(): Add Delay to Your Code (Example)
Python sleep() is a function used to delay the execution of code for the number of seconds given as input to sleep(). The sleep() command is a part of the time module. You can use the sleep() function to temporarily halt the execution of your code. For example, you are waiting for a process to complete or a file upload.
time.sleep() Syntax
import time time.sleep(seconds)
Parameters
seconds: The number of seconds you want the execution of your code to be halted.
Example: Using sleep() function in Python
Follow the steps given below to add sleep() in your python script.
Step 2: Add time.sleep()
The number 5 given as input to sleep(), is the number of seconds you want the code execution to halt when it is executed.
Here is a working code along with messages inside print(), to show the delay of message display on the terminal when executed.
import time print("Welcome to guru99 Python Tutorials") time.sleep(5) print("This message will be printed after a wait of 5 seconds")
Welcome to guru99 Python Tutorials This message will be printed after a wait of 5 seconds
How to delay the execution of function using sleep()?
The example shown below has a function defined called display(). The display() function prints a message “Welcome to Guru99 Tutorials”. When the function is called, it will execute and display the message inside the terminal.
To add delay to the execution of the function, let us add the time.sleep in Python before making a call to the function. During the execution, Python time.sleep will halt there for the number of seconds given, and later the function display() will be called.
import time print('Code Execution Started') def display(): print('Welcome to Guru99 Tutorials') time.sleep(5) display() print('Function Execution Delayed')
Code Execution Started Welcome to Guru99 Tutorials Function Execution Delayed
What are the different ways to add a delay in Python Script?
Using sleep() function
We have seen a few examples earlier on how to use time.sleep(). Let us try a different example here using time.sleep().
The code has a for loop that will take the string variable and print each character with a delay of 1 seconds.
import time my_message = "Guru99" for i in my_message: print(i) time.sleep(1)
Using asyncio.sleep function available from (Python 3.4 or higher)
You can make use of asyncio.sleep with python version 3.4 and higher. To make use of the asyncio sleep method, you need to add async and await to the function, as shown in the example below:
The script has a function call display() that prints a message “Welcome to Guru99 tutorials”. There are two keywords used in the function async and await. The async keyword is added at the start of the function definition, and await is added just before the asyncio.sleep(). Both the keywords async / await are meant to handle the asynchronous task.
When the function display() is called, and it encounters await asyncio.sleep(5), the code will sleep or halt at that point for 5 seconds and, once done, will print the message.
import asyncio print('Code Execution Started') async def display(): await asyncio.sleep(5) print('Welcome to Guru99 Tutorials') asyncio.run(display())
Code Execution Started Welcome to Guru99 Tutorials
Using Event().wait
The Event().wait method comes from the threading module. Event.wait() method will halt the execution of any process for the number of seconds it takes as an argument. The working of Event is shown in the example below:
The code is using Event().wait(5).The number 5 is the number of seconds the code will delay to go to the next line that calls the function display(). Once the 5 seconds are done, the function display() will be called, and the message will be printed inside in the terminal.
from threading import Event print('Code Execution Started') def display(): print('Welcome to Guru99 Tutorials') Event().wait(5) display()
Code Execution Started Welcome to Guru99 Tutorials
Using Timer
The Timer is another method available with Threading, and it helps to get the same functionality as Python time sleep. The working of the Timer is shown in the example below:
A Timer takes in input as the delay time in Python in seconds, along with a task that needs to be started. To make a timer working, you need to call the start() method. In the code, the Timer is given 5 seconds, and the function display that has to be called when 5 seconds are done. The timer will start working when the Timer.start() method is called.
from threading import Timer print('Code Execution Started') def display(): print('Welcome to Guru99 Tutorials') t = Timer(5, display) t.start()
Code Execution Started Welcome to Guru99 Tutorials
Summary
- Python sleep() function will pause Python code or delay the execution of program for the number of seconds given as input to sleep(). The sleep() function is part of the Python time module.
- You can make use of Python sleep function when you want to temporarily halt the execution of your code. For example, in case you are waiting for another process to complete, or a file upload, etc.
- There are many ways to add Python delay function to code besides sleep, and they are using asyncio.sleep , Event().wait and Timer.
- Similar to sleep() method, there is asyncio.sleep() method with python version 3.4 and higher. To make use of the asyncio sleep method, you need to add async and await to the function
- The Event().wait method comes from the threading module. Event.wait() method will halt the execution of any process for the number of seconds it takes as an argument.
- The Timer is another method available with Threading, and it helps to get the same functionality as sleep