How can I make a time delay in Python?

ID : 187

viewed : 447

Tags : pythonpython-3.xdelaysleeptimedelaypython

Top 5 Answer for How can I make a time delay in Python?

vote vote


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). 
vote vote


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


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 


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.

vote vote


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:


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')) 
vote vote


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) 

Top 3 video Explaining How can I make a time delay in Python?