Hàm delay trong Python

This function actually suspends the processing of the thread in which it is called by the operating system, allowing other threads and processes to execute while it sleeps.

Use it for that purpose, or simply to delay a function from executing. For example:

>>> def party_time[]:
...     print['hooray!']
...
>>> sleep[3]; party_time[]
hooray!

"hooray!" is printed 3 seconds after I hit Enter.

Example using sleep with multiple threads and processes

Again, sleep suspends your thread - it uses next to zero processing power.

To demonstrate, create a script like this [I first attempted this in an interactive Python 3.5 shell, but sub-processes can't find the party_later function for some reason]:

from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed
from time import sleep, time

def party_later[kind='', n='']:
    sleep[3]
    return kind + n + ' party time!: ' + __name__

def main[]:
    with ProcessPoolExecutor[] as proc_executor:
        with ThreadPoolExecutor[] as thread_executor:
            start_time = time[]
            proc_future1 = proc_executor.submit[party_later, kind='proc', n='1']
            proc_future2 = proc_executor.submit[party_later, kind='proc', n='2']
            thread_future1 = thread_executor.submit[party_later, kind='thread', n='1']
            thread_future2 = thread_executor.submit[party_later, kind='thread', n='2']
            for f in as_completed[[
              proc_future1, proc_future2, thread_future1, thread_future2,]]:
                print[f.result[]]
            end_time = time[]
    print['total time to execute four 3-sec functions:', end_time - start_time]

if __name__ == '__main__':
    main[]

Example output from this script:

thread1 party time!: __main__
thread2 party time!: __main__
proc1 party time!: __mp_main__
proc2 party time!: __mp_main__
total time to execute four 3-sec functions: 3.4519670009613037

Multithreading

You can trigger a function to be called at a later time in a separate thread with the Timer threading object:

>>> from threading import Timer
>>> t = Timer[3, party_time, args=None, kwargs=None]
>>> t.start[]
>>>
>>> hooray!

>>>

The blank line illustrates that the function printed to my standard output, and I had to hit Enter to ensure I was on a prompt.

The upside of this method is that while the Timer thread was waiting, I was able to do other things, in this case, hitting Enter one time - before the function executed [see the first empty prompt].

There isn't a respective object in the multiprocessing library. You can create one, but it probably doesn't exist for a reason. A sub-thread makes a lot more sense for a simple timer than a whole new subprocess.

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

Chủ Đề