How can I make a time delay?

3,502,196

Solution 1

import time
time.sleep(5)   # Delays for 5 seconds. You can also use a float value.

Here is another example where something is run approximately once a minute:

import time
while True:
    print("This prints once a minute.")
    time.sleep(60) # Delay for 1 minute (60 seconds).

Solution 2

You can use the sleep() function in the time module. It can take a float argument for sub-second resolution.

from time import sleep
sleep(0.1) # Time in seconds

Solution 3

How can I make a time delay in Python?

In a single thread I suggest the sleep function:

>>> from time import sleep

>>> sleep(4)

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.

Solution 4

Delays can be also implemented by using the following methods.

The first method:

import time
time.sleep(5) # Delay for 5 seconds.

The second method to delay would be using the implicit wait method:

 driver.implicitly_wait(5)

The third method is more useful when you have to wait until a particular action is completed or until an element is found:

self.wait.until(EC.presence_of_element_located((By.ID, 'UserName'))

Solution 5

There are five methods which I know: time.sleep(), pygame.time.wait(), matplotlib's pyplot.pause(), .after(), and asyncio.sleep().


time.sleep() example (do not use if using tkinter):

import time
print('Hello')
time.sleep(5) # Number of seconds
print('Bye')

pygame.time.wait() example (not recommended if you are not using the pygame window, but you could exit the window instantly):

import pygame
# If you are going to use the time module
# don't do "from pygame import *"
pygame.init()
print('Hello')
pygame.time.wait(5000) # Milliseconds
print('Bye')

matplotlib's function pyplot.pause() example (not recommended if you are not using the graph, but you could exit the graph instantly):

import matplotlib
print('Hello')
matplotlib.pyplot.pause(5) # Seconds
print('Bye')

The .after() method (best with Tkinter):

import tkinter as tk # Tkinter for Python 2
root = tk.Tk()
print('Hello')
def ohhi():
    print('Oh, hi!')
root.after(5000, ohhi) # Milliseconds and then a function
print('Bye')

Finally, the asyncio.sleep() method:

import asyncio
asyncio.sleep(5)
Share:
3,502,196
user46646
Author by

user46646

Updated on April 17, 2022

Comments

  • user46646
    user46646 about 2 years

    I would like to know how to put a time delay in a Python script.

  • ssj
    ssj about 10 years
    if you need some conditions to happen. It better to user threading.Event.wait.
  • Parthian Shot
    Parthian Shot almost 9 years
    Well... it'll print less frequently than that, because it takes time to print and handle all the buffers that entails (possibly doing a kernel context switch), and to register the alarm signal, but... yeah. A little under once per minute.
  • DonGru
    DonGru almost 7 years
    when using tkinter as graphical user interface, sleep() won't do the job - use after() instead: tkinter.Tk.after(yourrootwindow,60000) or yourrootwindow.after(60000)
  • SDsolar
    SDsolar about 6 years
    It is worth mentioning that in Windows the best granularity you can hope for is about 0.015 seconds (15 ms) accuracy. Most versions of Linux on modern processors can get down to 0.001 seconds (1 ms) granularity.
  • Artemis
    Artemis about 6 years
    @SDsolar What is wrong with sleep: You can't do any processing while it is sleeping, it basically puts the program on hold.
  • SDsolar
    SDsolar about 6 years
    Indeed. The tkinter comment would be better presented as an answer instead of in a comment. We're building a database here that will be around for years to come, with people finding answers via Google, and lots of people never get around to reading the comments. This would make a great new question, even. Something along the lines of "How to make a time delay in Python while using tkinter" or similar.
  • alexandernst
    alexandernst about 6 years
    The second and the third method are not Python per-se, but selenium related. And you'd use them when you're doing E2E tests. OP hasn't mentioned about any of those.
  • Peter Mortensen
    Peter Mortensen almost 6 years
    Yes, but what can be said about the actual time resolution on different platforms? Are there some guarantees? Could the resolution be 16.666 ms?
  • Keith Ripley
    Keith Ripley about 5 years
    Don't use this solution. It may technically work, but it will eat your CPU. Modern hardware and operating systems have better ways of creating time delays that don't hog system resources. Use time.sleep() instead.
  • Boris Verkhovskiy
    Boris Verkhovskiy almost 5 years
    @PeterMortensen did you see SDsolar's comment? If you need guarantees you should be using a real time operating system and shouldn't be using a garbage collected language.
  • srrvnn
    srrvnn over 4 years
    Why is this better than time.sleep()?
  • Aaron_ab
    Aaron_ab over 4 years
    Try running similar example with time.sleep. You will not get same running time results. Recommend to read about asynchronous programming in python
  • Corey Goldberg
    Corey Goldberg over 4 years
    this is basically a mini tutorial on imports, which the OP never asked about. This answer could be replaced with "use time.sleep()"
  • Corey Goldberg
    Corey Goldberg over 4 years
    driver.implicitly_wait() is a selenium webdriver method that sets the default wait time for finding elements on a web page. It is totally irrelevant to the question asked.
  • mabraham
    mabraham over 4 years
    The original question was about inserting a delay. That nail needs a hammer, not an asynchronous wrench :-)
  • Peter Mortensen
    Peter Mortensen over 4 years
    What about the time resolution? E.g., is there a risk of it being a multiple of 16.66 ms (though in the example it would happen to be exactly 0.1 second, 6 multiples of 16.66 ms)? Or is e.g. at least 1 ms guaranteed? For example, could a specified delay of 3 ms actually result in a 17 ms delay?
  • Saad Anees
    Saad Anees over 4 years
    its working for the first time.. second time its giving error 'RuntimeError: threads can only be started once'
  • Trenton
    Trenton over 2 years
    Yes, modern, like anything from the last 4-5 decades.