Python sleep function usage with examples

Read Time:8 Minute, 59 Second

Table of Contents

The sleep() function suspends (waits) the current thread’s execution for a specified number of seconds. Python offers a time module that contains various useful functions for dealing with time-related activities. sleep() is one of the most prominent roles among them.

Python sleep function

The sleep() function suspends the current thread’s execution for a specified amount of seconds.

Sleep() takes a floating-point number as a parameter, as you can see in the sample above. Earlier than Python 3.5, the actual suspension time could be shorter than the time() function’s parameter. Since Python 3.5, the suspension time will be at least the seconds specified.

Example: Creating a digital clock

We computed and reported the current local time within the infinite while loop in the preceding program. The program then waits one second. The current local time is calculated and printed once again. This procedure continues. When you run the software, you should see something like this:


Creating a digital clock

Here’s a slightly improved version of the previous program.

Python multithreading

Let’s discuss processes and threads before discussing sleep() in multithreaded systems. A set of instructions makes up a computer program. The execution of those instructions is referred to as a process.

The procedure is divided into threads. In a process, there can be one or more threads.

Example: Multithreading in Python

All of the programs mentioned earlier in this article are single-threaded. A multithreaded Python program is shown below.


When you run the software, you should see something like this:

Multithreading in Python
Multithreading in Python

There are two threads in the above software, thread_one, and thread_two. The thread_one.start() and thread_two.start() commands are used to start these threads. Note that thread_one and thread_two run at the same time. Thus, the results may differ.

In multithreaded programs, use time.sleep().

The sleep() function suspends the current thread’s execution for a specified amount of seconds. sleep() suspends the thread and process execution in single-threaded programs. However, in multithreaded systems, the function suspends a thread rather than the entire process.

Example: sleep() method in a multithreaded program


There are two threads in the above application. We have made use of time.sleep(0.25), and time.sleep(0.5) respectively halt the execution of these two threads for 0.25 and 0.5 seconds.

Using Decorators to Add a Python sleep() Call

There are situations when you need to retry a failed function. It is a common use case when you need to retry a file download because the server was temporarily unavailable. Because you won’t want to make too many requests to the server, adding a Python sleep() call between each one is recommended.

Another scenario we’ve encountered is when we need to verify the condition of a user interface during an automated test. Depending on the computer I’m testing on, the user interface may load faster or slower than usual. It may alter what is displayed on the screen while my software confirms anything.

In this scenario, we can tell the program to sleep for a second or two before checking things again. It could spell the difference between passing and failing an exam.

You can use a decorator to add a Python sleep() system call in either of these scenarios. Check out Primer on Python Decorators if you’re unfamiliar with decorators or want to brush up on them.


Consider the following scenario:

Your decorator is code_sleep(). It takes a timeout value and a retry count, set to three by default. Another function, code_decorator(), is contained within code_sleep() and accepts the decorated function.

Finally, wrapper(), the innermost function, accepts the arguments and keyword arguments passed to the decorated function. It’s here that the magic happens! To retry invoking the method, you use a while loop. You call time if there is an exception. Try executing the code again after using sleep() and incrementing the retries counter.

To use your new decorator, edit code_uptime_bot() as follows:

You use a 2 second code_sleep() to embellish code_uptime_bot(). You’ve also got rid of the original while loop and the old sleep call (60). The decorator now handles this.


Another improvement you made was to include a raise within the exception handling sections. It is so the decorator can do his job properly. You could modify the decorator to handle these failures, but as these exceptions only apply to urllib, it’s probably best to leave things alone. It will then be compatible with a wider range of functions.

There are a few things you could do to improve your decorator. You may make it re-raise the last mistake if it runs out of retries and still fails. The decorator will also wait 2 seconds after the previous failure, which you may not want to happen. Feel free to use them as a workout!

Using Async IO with a Python sleep() call

Python’s asynchronous capabilities were added in version 3.4, and the feature set has been rapidly developing since then. Asynchronous programming allows you to run numerous tasks at the same time. The main thread will be notified when a job is completed.

asyncio is a module that allows you to append a Python sleep() function asynchronously. Here’s an example is taken from the Python documentation:


In this example, between two print() statements, you run main() and let it sleep for one second. Here’s a more striking example from the asyncio documentation’s Coroutines and Tasks section:

You create a code_output() worker with the number of seconds to sleep and the text to print out in this code. The await keyword in Python is then used to wait for the output() code to run. Because output() is an async function, you can’t call it a regular function without using await.

Your application will run three times if you run this code. For 6 seconds, the code will wait for 1, 2, and 3 seconds. You can also change the code to run the tasks simultaneously:

You’re now using the task notion, which you may construct with create_task(). When you use asyncio with tasks, Python runs them asynchronously. As a result, running the code above should take 3 seconds instead of 6.

Adding a Python sleep() Call in GUI

Python sleep() calls aren’t only useful in command-line applications. Sometimes, you’ll need to add delays to your Graphical User Interface (GUI). For example, you might write an FTP program that downloads millions of files, but you’ll need to include a sleep() call in between batches to avoid slowing down the server.


The event loop refers to the main thread in which GUI code runs all its processing and painting.

If you use time.sleep() in GUI code, the event loop will be blocked. The application may appear to freeze from the user’s perspective. This approach prevents the user from interacting with your application while sleeping. (On Windows, you can get a notification that your application has become unresponsive.)

Fortunately, there are alternatives to relying on time.sleep(). We’ll explore how to add Python sleep() calls to Tkinter and wxPython in the following sections.

Sleeping Concept in Tkinter

The Python standard library includes tkinter. Just in case you’re using a pre-installed version of Python on Linux or Mac, it might not be available. If you receive an ImportError, you must investigate how to add it to your system. Further, Tkinter should be available right away if you install Python yourself. We’ll begin by looking at an example utilizing time.sleep(). To show what occurs when you add a Python sleep() call the wrong way, run this code:


Once the code has been run, press the button on your GUI. The button will remain pressed for three seconds as it waits for sleep() to complete. You wouldn’t be able to click other buttons if the application had them. You won’t be able to close the app while it’s asleep because it won’t respond to the close event. You’ll need to use after() to get Tkinter to sleep properly:

The code above creates an application with a width of 400 pixels and a height of 400 pixels. It is devoid of widgets. It will only display a frame. Then you call self.root.after(), where self.root is a Tk() object reference. after() has two parameters:

  • The duration of sleep in milliseconds
  • When the sleep is over, invoke this function.

After 3 seconds, your application will print a string to stdout in this scenario. after() can be thought of as the Tkinter version of time.sleep() is similar to sleep(), except it adds the ability to call a function once the sleep is complete.

You might utilize this feature to enhance the user experience. You can make the program appear to load faster by adding a Python sleep() call and then start a longer-running process once it’s up. The user will not have to wait for the application to open.

Example: Countdown script with Python sleep() function

Example: Sleep function () in multithreading in Python

Example: Using sleep() to Delay the Execution of a Function

Example: How to Add a Python sleep() call with Threads


Thanks to this lesson, you’ve learned a useful new approach to add to your Python toolkit! You know how to pace your programs and keep them from hogging system resources by adding delays. sleep() calls in Python can even help your GUI programs redraw more efficiently. It will greatly improve your consumers’ experience!


Have you ever needed to wait for something in your Python program? You want your code to run as rapidly as possible most of the time. However, there are occasions when putting your code to sleep is in your best interests. To mimic a delay in your software, you may use the Python sleep() function. You might have to wait for a file to upload or download a graphic to load or be drawn to the screen. You might even need to break between calls to a web API or database queries. In each of these scenarios, and many others, adding Python sleep() calls to your application will assist!


Tag Cloud

Java Java Logical Programs OTP Generation in Java python Recursion youtube video ASCII Upper and Lower Case blockchain javascript graph learn to code software development Successful Software Engineers breadth first search Java Array Programs Java Programs Uncategorized android ios programming kotlin web-development django data sql cybersecurity database swiftui serverless aws swift rust react background-position gradients loader mask grid nth-child pseudo elements indieweb WordPress Print Array without brackets C++ factorial Java String Programs Final Keyword Static Variable Axie Infinity Cryptokitties NFT games tool inserting MISC Tips Codes python code python projects python3 system info python project Bigginers How to Do Integrations Payment Gateways PHP checkout page in php Implement stripe payment gateway in Step by step in PHP integrate stripe gatway in php mysql payment gateway integration in php step by step payment gateway integration in php step by step with source code payment gateway integration in website PHP Integrate Stripe Payment Gateway Tutorial PHP shopping cart checkout code shopping cart in php stripe php checkout PHP/MySQL/JSON best international payment gateway does google pay accept international payments how to accept international payments in india paytm payment gateway razorpay codeigniter github razorpay custom checkout github razorpay get payment details razorpay integration in codeigniter github razorpay international payments Razorpay payment gateway integration in CodeIgniter razorpay payment gateway integration in php code Razorpay payment gateway integration with PHP and CodeIgniter Razorpay payment gateway setup in CodeIgniter Library & Frameworks Tips & Tricks UI/UX & Front-end coding birds online html code for google sign in login with google account in PHP login with google account using javascript login with google account using javascript codeigniter login with google account using php login with google account using php source code
Improving Icons for UI Elements with Typographic Alignment and Scale Previous post Improving Icons for UI Elements with Typographic Alignment and Scale
An Interactive Starry Backdrop for Content Next post An Interactive Starry Backdrop for Content

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.