Hàm sleep trong Python

While running a Python program, there might be times when you'd like to delay the execution of the program for some seconds.

The Python time module has a built-in function called time.sleep[] with which you can delay the execution of a program.

With the sleep[] function, you can get more creative in your Python projects because it lets you create delays that might go a long way in helping you bring in certain functionalities.

In this article, you will learn how to use the time.sleep[] method to create delays.

Just note that delays created with time.sleep[] do not stop the execution of the whole program – they only delay the current thread.

Basic Syntax of time.sleep[]

To use time.sleep[] in your program, you have to import it from the time module first.

After importing the

import time

print["Hello world"]

time.sleep[5]

print["Hello campers"]
0 function, specify the number of seconds you want the delay to run inside the parenthesis.

import time
time.sleep[delayInSeconds]

Basic Example of time.sleep[]

In the code snippet below, I put a delay of 5 seconds between the 2 print statements, so the second print statement will run 5 seconds after the first print statement runs:

import time

print["Hello world"]

time.sleep[5]

print["Hello campers"]

You can also specify the delay in floating-point numbers:

import time

print["Hello world"]

time.sleep[3.5]

print["Hello campers"]

More Examples of time.sleep[]

You can get more creative with delays created by time.sleep[] by combining it with

import time

print["Hello world"]

time.sleep[5]

print["Hello campers"]
2, another built-in function from the time module that stands for “current time”.

import time

print["Execution started at: ", time.ctime[]]

time.sleep[10]
print["Hello world"]

print["Execution ended at at: ", time.ctime[]]

# Output
# Executiuon started at:  Thu Mar 17 10:37:55 2022
# Hello world
# Executiuon ended at at:  Thu Mar 17 10:38:05 2022

You can also use time.sleep[] to create multiple delays while looping through iterable data such as list or tuple.

The example below shows how I did it with a list:

import time

# Creating the list
legendaryFootballers = ["Okocha", "Pele", "Eusebio", "Martha", "Cruyff", "MAradona"]

for legend in legendaryFootballers:

    # Creating the delay
    time.sleep[2]

    # Individual legends in the list will be printed after 2 seconds
    print[legend]

The output:

Conclusion

This article took you through how to use the time.sleep[] function in Python.

time.sleep[] is an exciting built-in function that can be useful for creating delays in your Python projects, whether they're games, web projects, or AI systems.

Keep coding!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Kolade Chris

Web developer and technical writer focusing on frontend technologies.

If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Have you ever needed to make your Python program wait for something? Most of the time, you’d 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

$ python3 -m timeit -n 3 "import time; time.sleep[3]"
3 loops, best of 5: 3 sec per loop
5 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
$ python3 -m timeit -n 3 "import time; time.sleep[3]"
3 loops, best of 5: 3 sec per loop
5 calls to your program can help in each of these cases, and many more!

In this tutorial, you’ll learn how to add Python

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

  • $ python3 -m timeit -n 3 "import time; time.sleep[3]"
    3 loops, best of 5: 3 sec per loop
    
    8
  • 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 let’s get started!

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

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

Python has built-in support for putting your program to sleep. The

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]
1 module has a function that you can use to suspend execution of the calling thread for however many seconds you specify.

Here’s an example of how to use

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

>>>

>>> 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

$ python3 -m timeit -n 3 "import time; time.sleep[3]"
3 loops, best of 5: 3 sec per loop
8 slightly. The new Python
$ python3 -m timeit -n 3 "import time; time.sleep[3]"
3 loops, best of 5: 3 sec per loop
5 system call will last at least the number of seconds you’ve 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 Python’s

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]
6 module:

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

Here, you run the

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]
6 module with the
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]
8 parameter, which tells
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]
6 how many times to run the statement that follows. You can see that
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]
6 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

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]
6 will run your code is one million. If you were to run the above code with the default
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]
8, then at 3 seconds per iteration, your terminal would hang for approximately 34 days! The
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]
6 module has several other command line options that you can check out in its .

Let’s 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 website’s status code regularly, but you can’t query the web server constantly or it will affect performance. One way to do this check is to use a Python

$ python3 -m timeit -n 3 "import time; time.sleep[3]"
3 loops, best of 5: 3 sec per loop
5 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

HTTPError: 404 for //www.google.com/py
5, which takes a URL as its argument. The function then attempts to open that URL with
HTTPError: 404 for //www.google.com/py
6. If there’s an
HTTPError: 404 for //www.google.com/py
7 or
HTTPError: 404 for //www.google.com/py
8, 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

HTTPError: 404 for //www.google.com/py
9. 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
$ python3 -m timeit -n 3 "import time; time.sleep[3]"
3 loops, best of 5: 3 sec per loop
5 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 won’t want to make a request to the server too often, so adding a Python

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

Another use case that I’ve 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 I’m running the test on. This can change what’s 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

$ python3 -m timeit -n 3 "import time; time.sleep[3]"
3 loops, best of 5: 3 sec per loop
5 system call in either of these cases. If you’re not familiar with decorators, or if you’d like to brush up on them, then check out Primer on Python Decorators. Let’s 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 

Chủ Đề