How do I add a delay in Pygame?

Python sleep[]: How to Add Time Delays to Your Code

by Mike Driscoll intermediate python
Mark as Completed
Tweet Share Email

Table of Contents

  • Adding a Python sleep[] Call With time.sleep[]
  • Adding a Python sleep[] Call With Decorators
  • Adding a Python sleep[] Call With Threads
    • Using time.sleep[]
    • Using Event.wait[]
  • Adding a Python sleep[] Call With Async IO
  • Adding a Python sleep[] Call With GUIs
    • Sleeping in Tkinter
    • Sleeping in wxPython
  • Conclusion
Remove ads

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Using sleep[] to Code a Python Uptime Bot

Have you ever needed to make your Python program wait for something? Most of the time, youd want your code to execute as quickly as possible. But there are times when letting your code sleep for a while is actually in your best interest.

For example, you might use a Python sleep[] call to simulate a delay in your program. Perhaps you need to wait for a file to upload or download, or for a graphic to load or be drawn to the screen. You might even need to pause between calls to a web API, or between queries to a database. Adding Python sleep[] calls to your program can help in each of these cases, and many more!

In this tutorial, youll learn how to add Python sleep[] calls with:

  • time.sleep[]
  • Decorators
  • Threads
  • Async IO
  • Graphical User Interfaces

This article is intended for intermediate developers who are looking to grow their knowledge of Python. If that sounds like you, then lets get started!

Free Bonus: Get our free "The Power of Python Decorators" guide that shows you 3 advanced decorator patterns and techniques you can use to write to cleaner and more Pythonic programs.

Adding a Python sleep[] Call With time.sleep[]

Python has built-in support for putting your program to sleep. The time module has a function sleep[] that you can use to suspend execution of the calling thread for however many seconds you specify.

Heres an example of how to use time.sleep[]:

>>>>>> import time >>> time.sleep[3] # Sleep for 3 seconds

If you run this code in your console, then you should experience a delay before you can enter a new statement in the REPL.

Note: In Python 3.5, the core developers changed the behavior of time.sleep[] slightly. The new Python sleep[] system call will last at least the number of seconds youve specified, even if the sleep is interrupted by a signal. This does not apply if the signal itself raises an exception, however.

You can test how long the sleep lasts by using Pythons timeit module:

$ python3 -m timeit -n 3 "import time; time.sleep[3]" 3 loops, best of 5: 3 sec per loop

Here, you run the timeit module with the -n parameter, which tells timeit how many times to run the statement that follows. You can see that timeit ran the statement 3 times and that the best run time was 3 seconds, which is what was expected.

The default number of times that timeit will run your code is one million. If you were to run the above code with the default -n, then at 3 seconds per iteration, your terminal would hang for approximately 34 days! The timeit module has several other command line options that you can check out in its documentation.

Lets create something a bit more realistic. A system administrator needs to know when one of their websites goes down. You want to be able to check the websites status code regularly, but you cant query the web server constantly or it will affect performance. One way to do this check is to use a Python sleep[] system call:

import time import urllib.request import urllib.error def uptime_bot[url]: while True: try: conn = urllib.request.urlopen[url] except urllib.error.HTTPError as e: # Email admin / log print[f'HTTPError: {e.code} for {url}'] except urllib.error.URLError as e: # Email admin / log print[f'URLError: {e.code} for {url}'] else: # Website is up print[f'{url} is up'] time.sleep[60] if __name__ == '__main__': url = '//www.google.com/py' uptime_bot[url]

Here you create uptime_bot[], which takes a URL as its argument. The function then attempts to open that URL with urllib. If theres an HTTPError or URLError, then the program catches it and prints out the error. [In a live environment, you would log the error and probably send out an email to the webmaster or system administrator.]

If no errors occur, then your code prints out that all is well. Regardless of what happens, your program will sleep for 60 seconds. This means that you only access the website once every minute. The URL used in this example is bad, so it will output the following to your console once every minute:

HTTPError: 404 for //www.google.com/py

Go ahead and update the code to use a known good URL, like //www.google.com. Then you can re-run it to see it work successfully. You can also try to update the code to send an email or log the errors. For more information on how to do this, check out Sending Emails With Python and Logging in Python.

Remove ads

Adding a Python sleep[] Call With Decorators

There are times when you need to retry a function that has failed. One popular use case for this is when you need to retry a file download because the server was busy. You usually wont want to make a request to the server too often, so adding a Python sleep[] call between each request is desirable.

Another use case that Ive personally experienced is where I need to check the state of a user interface during an automated test. The user interface might load faster or slower than usual, depending on the computer Im running the test on. This can change whats on the screen at the moment my program is verifying something.

In this case, I can tell the program to sleep for a moment and then recheck things a second or two later. This can mean the difference between a passing and failing test.

You can use a decorator to add a Python sleep[] system call in either of these cases. If youre not familiar with decorators, or if youd like to brush up on them, then check out Primer on Python Decorators. Lets look at an example:

import time import urllib.request import urllib.error def sleep[timeout, retry=3]: def the_real_decorator[function]: def wrapper[*args, **kwargs]: retries = 0 while retries 0: await asyncio.sleep[1] print[f'{text} counter: {sleep} seconds'] sleep -= 1 async def main[]: task_1 = asyncio.create_task[output['First', 1]] task_2 = asyncio.create_task[output['Second', 2]] task_3 = asyncio.create_task[output['Third', 3]] print[f"Started: {time.strftime['%X']}"] await task_1 await task_2 await task_3 print[f"Ended: {time.strftime['%X']}"] if __name__ == '__main__': asyncio.run[main[]]

Now youre using the concept of tasks, which you can make with create_task[]. When you use tasks in asyncio, Python will run the tasks asynchronously. So, when you run the code above, it should finish in 3 seconds total instead of 6.

Remove ads

Adding a Python sleep[] Call With GUIs

Command-line applications arent the only place where you might need to add Python sleep[] calls. When you create a Graphical User Interface [GUI], youll occasionally need to add delays. For example, you might create an FTP application to download millions of files, but you need to add a sleep[] call between batches so you dont bog down the server.

GUI code will run all its processing and drawing in a main thread called the event loop. If you use time.sleep[] inside of GUI code, then youll block its event loop. From the users perspective, the application could appear to freeze. The user wont be able to interact with your application while its sleeping with this method. [On Windows, you might even get an alert about how your application is now unresponsive.]

Fortunately, there are other methods you can use besides time.sleep[]. In the next few sections, youll learn how to add Python sleep[] calls in both Tkinter and wxPython.

Sleeping in Tkinter

tkinter is a part of the Python standard library. It may not be available to you if youre using a pre-installed version of Python on Linux or Mac. If you get an ImportError, then youll need to look into how to add it to your system. But if you install Python yourself, then tkinter should already be available.

Youll start by looking at an example that uses time.sleep[]. Run this code to see what happens when you add a Python sleep[] call the wrong way:

import tkinter import time class MyApp: 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 = MyApp[root] root.mainloop[]

Once youve run the code, press the button in your GUI. The button will stick down for three seconds as it waits for sleep[] to finish. If the application had other buttons, then you wouldnt be able to click them. You cant close the application while its sleeping, either, since it cant respond to the close event.

To get tkinter to sleep properly, youll need to use after[]:

import tkinter class MyApp: 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['I was delayed'] if __name__ == "__main__": root = tkinter.Tk[] app = MyApp[root] root.mainloop[]

Here you create an application that is 400 pixels wide by 400 pixels tall. It has no widgets on it. All it will do is show a frame. Then, you call self.root.after[] where self.root is a reference to the Tk[] object. after[] takes two arguments:

  1. The number of milliseconds to sleep
  2. The method to call when the sleep is finished

In this case, your application will print a string to stdout after 3 seconds. You can think of after[] as the tkinter version of time.sleep[], but it also adds the ability to call a function after the sleep has finished.

You could use this functionality to improve user experience. By adding a Python sleep[] call, you can make the application appear to load faster and then start some longer-running process after its up. That way, the user wont have to wait for the application to open.

Sleeping in wxPython

There are two major differences between wxPython and Tkinter:

  1. wxPython has many more widgets.
  2. wxPython aims to look and feel native on all platforms.

The wxPython framework is not included with Python, so youll need to install it yourself. If youre not familiar with wxPython, then check out How to Build a Python GUI Application With wxPython.

In wxPython, you can use wx.CallLater[] to add a Python sleep[] call:

import wx class MyFrame[wx.Frame]: def __init__[self]: super[].__init__[parent=None, title='Hello World'] wx.CallLater[4000, self.delayed] self.Show[] def delayed[self]: print['I was delayed'] if __name__ == '__main__': app = wx.App[] frame = MyFrame[] app.MainLoop[]

Here, you subclass wx.Frame directly and then call wx.CallLater[]. This function takes the same parameters as Tkinters after[]:

  1. The number of milliseconds to sleep
  2. The method to call when the sleep is finished

When you run this code, you should see a small blank window appear without any widgets. After 4 seconds, youll see the string 'I was delayed' printed to stdout.

One of the benefits of using wx.CallLater[] is that its thread-safe. You can use this method from within a thread to call a function thats in the main wxPython application.

Remove ads

Conclusion

With this tutorial, youve gained a valuable new technique to add to your Python toolbox! You know how to add delays to pace your applications and prevent them from using up system resources. You can even use Python sleep[] calls to help your GUI code redraw more effectively. This will make the user experience much better for your customers!

To recap, youve learned how to add Python sleep[] calls with the following tools:

  • time.sleep[]
  • Decorators
  • Threads
  • asyncio
  • Tkinter
  • wxPython

Now you can take what youve learned and start putting your code to sleep!

Mark as Completed

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Using sleep[] to Code a Python Uptime Bot

Python Tricks

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Send Me Python Tricks »

About Mike Driscoll

Mike has been programming in Python for over a decade and loves writing about Python!

» More about Mike

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Aldren

Geir Arne

Jaya

Jon

Joanna

Master Real-World Python Skills With Unlimited Access to RealPython

Join us and get access to hundreds of tutorials, hands-on video courses, and a community of expertPythonistas:

Level Up Your Python Skills »

Master Real-World Python Skills
With Unlimited Access to RealPython

Join us and get access to hundreds of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

What Do You Think?

Tweet Share Email

Real Python Comment Policy: The most useful comments are those written with the goal of learning from or helping out other readersafter reading the whole article and all the earlier comments. Complaints and insults generally wont make the cut here.

Whats your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Keep Learning

Related Tutorial Categories: intermediate python

Recommended Video Course: Using sleep[] to Code a Python Uptime Bot

Keep reading RealPython by creating a free account or signingin:

Continue »

Already have an account? Sign-In

Video liên quan

Chủ Đề