Python sleep function usage

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.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import time

print("before executing the sleep function.")
time.sleep(5)
print("This information is printed after 5 seconds have elapsed.")</pre>
</div>

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

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import time

while True:
  current_localtime = time.localtime()
  rs_time = time.strftime("%%I:%%M:%%S %%p", current_localtime)
  print( rs_time )
  time.sleep(1)</pre>
</div>

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.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import time

while True:
  current_localtime = time.localtime()
  rst_time = time.strftime("%%I:%%M:%%S %%p", current_localtime)
  print(rst_time, end="", flush=True)
  print("\r", end="", flush=True)
  time.sleep(1)
</pre>
</div>

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.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import threading
  
def code_greetings():
  for i in range(5):
    print("code")
  
def code_count():
  for i in range(5):
    print(i)

thread_one = threading.Thread(target=code_greetings)  
thread_two = threading.Thread(target=code_count)  

thread_one.start()
thread_two.start()</pre>
</div>

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

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import threading
import time
  
def code_greetings():
  for i in range(4):
    time.sleep(0.25)
    print("code")
  
def code_count():
    for i in range(5):
      time.sleep(0.5)
      print(i)

thread_one = threading.Thread(target=code_greetings)  
thread_two = threading.Thread(target=code_count)  
thread_one.start()
thread_two.start()</pre>
</div>

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:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import time
import urllib.request
import urllib.error

def code_sleep(timeout, try_times=2):

    def code_decorator(function):
        def wrapper(*args, **kwargs):
            cd_retries = 0
            while cd_retries < try_times:
                try:
                    result_val = function(*args, **kwargs)
                    if result_val is None:
                        return
                except:
                    print(f'Sleeps for {timeout} seconds')
                    time.sleep(timeout)
                    cd_retries  += 1
        return wrapper
    return code_decorator</pre>
</div>

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:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>@code_sleep(3)
def code_uptime_bot(url):
    try:
        conn = urllib.request.urlopen(url)
    except urllib.error.HTTPError as e:
        # Email admin / log
        print(f'HTTPError: {e.code} for {url}')
        # Re-raise the exception for the decorator
        raise urllib.error.HTTPError
    except urllib.error.URLError as e:
        # Email admin / log
        print(f'URLError: {e.code} for {url}')
        # Re-raise the exception for the decorator
        raise urllib.error.URLError
    else:
        # Website is up
        print(f'{url} is up')

if __name__ == '__main__':
    url = 'https://thirdeyemedia.wpmudev.host/codeunderscored/'
    code_uptime_bot(url)
</pre>
</div>

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:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import asyncio

async def main():
    print('Hello ...')
    await asyncio.sleep(1)
    print('... code!')

# Python 3.7+
asyncio.run(main())</pre>
</div>

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:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import asyncio
import time

async def output(sleep, text):
    await asyncio.sleep(sleep)
    print(text)

async def code_main():
    print(f"Started: {time.strftime('%%X')}")
    await output(1, 'One')
    await output(2, 'Two')
    await output(3, 'Three')
    print(f"Ended: {time.strftime('%%X')}")

# Python 3.7+
asyncio.run(code_main())
</pre>
</div>

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:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import asyncio
import time

async def code_output(text, sleep):
    while sleep > 0:
        await asyncio.sleep(1)
        print(f'{text} counter: {sleep} seconds')
        sleep -= 1

async def code_main():
    first_task = asyncio.create_task(code_output('First', 1))
    second_task = asyncio.create_task(code_output('Second', 2))
    first_task = asyncio.create_task(code_output('Third', 3))
    print(f"Started: {time.strftime('%%X')}")
    await first_task
    await second_task
    await third_task                              
    print(f"Ended: {time.strftime('%%X')}")

if __name__ == '__main__':
    asyncio.run(code_main())</pre>
</div>

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:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import tkinter
import time

class Code_App:
    def __init__(self, parent):
        self.root = parent
        self.root.geometry("400x400")
        self.frame = tkinter.Frame(parent)
        self.frame.pack()
        b = tkinter.Button(text="click me", command=self.delayed)
        b.pack()

    def delayed(self):
        time.sleep(3)

if __name__ == "__main__":
    root = tkinter.Tk()
    app = Code_App(root)
    root.mainloop()</pre>
</div>

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:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import tkinter

class Code_App:
    def __init__(self, parent):
        self.root = parent
        self.root.geometry("400x400")
        self.frame = tkinter.Frame(parent)
        self.frame.pack()
        self.root.after(3000, self.delayed)

    def delayed(self):
        print('some delay')

if __name__ == "__main__":
    root = tkinter.Tk()
    app = Code_App(root)
    root.mainloop()
</pre>
</div>

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

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import time

for i in reversed(range(1, 11)):
  print(i)

  time.sleep(1)

print("end")</pre>
</div>

Example: Sleep function () in multithreading in Python

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import time
import threading

def info():
	for i in range(5):
		print("Thread 1 is running")
		time.sleep(1)

def extra_info():
	for j in range(5):
		print("The second thread is running")
		time.sleep(1)
		first_thread =threading.Thread(targe=extra)
		first_thread.start()
		
		second_thread =threading.Thread(targe=extra_info)
		second_thread.start()</pre>
</div>

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

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import time
print("start of program execution")
x=120
y=30

def code_addition():
	print(x+y)
	time.sleep(5)
	
code_addition()
print("cod_addition() is executed after 5 seconds of delay")
</pre>
</div>

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

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>from threading import Thread
import time

site ="Codeunderscored"

class first(Thread):
	
	def run(self):
		for s in site:
			time.sleep(0.5)
			print("code: "+1)
			
class second(Thread):
	def run(self):
		time.sleep(5)
		print(site)
first().start()
second().start()
</pre>
</div>

Conclusion

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!

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *