By user46646


2009-02-04 07:04:09 8 Comments

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

13 comments

@Matthijs990 2019-04-13 06:09:22

You also can try this:

import time
# The time now
start = time.time() 
while time.time() - start < 10: # Run 1- seconds
    pass
# Do the job

Now the shell will not crash or not react.

@Keith Ripley 2019-04-23 20:15:45

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.

@BlackBeard 2019-01-10 12:13:25

If you would like to put a time delay in a Python script:

Use time.sleep or Event().wait like this:

from threading import Event
from time import sleep

delay_in_sec = 2

# Use time.sleep like this
sleep(delay_in_sec)         # Returns None
print(f'slept for {delay_in_sec} seconds')

# Or use Event().wait like this
Event().wait(delay_in_sec)  # Returns False
print(f'waited for {delay_in_sec} seconds')

However, if you want to delay the execution of a function do this:

Use threading.Timer like this:

from threading import Timer

delay_in_sec = 2

def hello(delay_in_sec):
    print(f'function called after {delay_in_sec} seconds')

t = Timer(delay_in_sec, hello, [delay_in_sec])  # Hello function will be called 2 seconds later with [delay_in_sec] as the *args parameter
t.start()  # Returns None
print("Started")

Outputs:

Started
function called after 2 seconds

Why use the later approach?

  • It does not stop execution of the whole script (except for the function you pass it).
  • After starting the timer you can also stop it by doing timer_obj.cancel().

@Saad Anees 2019-12-01 14:53:36

its working for the first time.. second time its giving error 'RuntimeError: threads can only be started once'

@Aaron_ab 2018-12-03 19:12:52

asyncio.sleep

Notice in recent Python versions (Python 3.4 or higher) you can use asyncio.sleep. It's related to asynchronous programming and asyncio. Check out next example:

import asyncio
from datetime import datetime

@asyncio.coroutine
def countdown(iteration_name, countdown_sec):
    """
    Just count for some countdown_sec seconds and do nothing else
    """
    while countdown_sec > 0:
       print(f'{iteration_name} iterates: {countdown_sec} seconds')
       yield from asyncio.sleep(1)
       countdown_sec -= 1

loop = asyncio.get_event_loop()
tasks = [asyncio.ensure_future(countdown('First Count', 2)),
         asyncio.ensure_future(countdown('Second Count', 3))]

start_time = datetime.utcnow()

# Run both methods. How much time will both run...?
loop.run_until_complete(asyncio.wait(tasks))

loop.close()

print(f'total running time: {datetime.utcnow() - start_time}')

We may think it will "sleep" for 2 seconds for first method and then 3 seconds in the second method, a total of 5 seconds running time of this code. But it will print:

total_running_time: 0:00:03.01286

It is recommended to read asyncio official documentation for more details.

@srrvnn 2019-09-12 15:56:54

Why is this better than time.sleep()?

@Aaron_ab 2019-09-12 16:17:15

Try running similar example with time.sleep. You will not get same running time results. Recommend to read about asynchronous programming in python

@mabraham 2019-10-11 15:27:18

The original question was about inserting a delay. That nail needs a hammer, not an asynchronous wrench :-)

@Parallax Sugar 2017-02-28 19:45:40

The Tkinter library in the Python standard library is an interactive tool which you can import. Basically, you can create buttons and boxes and popups and stuff that appear as windows which you manipulate with code.

If you use Tkinter, do not use time.sleep(), because it will muck up your program. This happened to me. Instead, use root.after() and replace the values for however many seconds, with a milliseconds. For example, time.sleep(1) is equivalent to root.after(1000) in Tkinter.

Otherwise, time.sleep(), which many answers have pointed out, which is the way to go.

@Tejas Joshi 2018-09-16 08:14:05

This is an easy example of a time delay:

import time

def delay(period='5'):
    # If the user enters nothing, it'll wait 5 seconds
    try:
        # If the user not enters a int, I'll just return ''
        time.sleep(period)
    except:
        return ''

Another, in Tkinter:

import tkinter

def tick():
    pass

root = Tk()
delay = 100 # Time in milliseconds
root.after(delay, tick)
root.mainloop()

@Trooper Z 2018-07-05 20:47:48

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


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&nbsp;2
root = tk.Tk()
print('Hello')
def ohhi():
    print('Oh, hi!')
root.after(5000, ohhi) # Milliseconds and then a function
print('Bye')

Finally, the driver.implicitly_wait() method (Selenium):

driver.implicitly_wait(5) # Waits 5 seconds

@Corey Goldberg 2019-09-23 04:59:50

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.

@Humble_boy 2018-01-05 10:41:24

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

@alexandernst 2018-05-05 08:28:09

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.

@Aaron Hall 2017-06-21 03:25:05

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.

@pobk 2008-09-15 16:34:29

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

@Peter Mortensen 2019-11-27 18:42:28

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?

@Matthew Miles 2017-06-13 19:04:18

Delays are done with the time library, specifically the time.sleep() function.

To just make it wait for a second:

from time import sleep
sleep(1)

This works because by doing:

from time import sleep

You extract the sleep function only from the time library, which means you can just call it with:

sleep(seconds)

Rather than having to type out

time.sleep()

Which is awkwardly long to type.

With this method, you wouldn't get access to the other features of the time library and you can't have a variable called sleep. But you could create a variable called time.

Doing from [library] import [function] (, [function2]) is great if you just want certain parts of a module.

You could equally do it as:

import time
time.sleep(1)

and you would have access to the other features of the time library like time.clock() as long as you type time.[function](), but you couldn't create the variable time because it would overwrite the import. A solution to this to do

import time as t

which would allow you to reference the time library as t, allowing you to do:

t.sleep()

This works on any library.

@Corey Goldberg 2019-09-23 04:57:59

this is basically a mini tutorial on imports, which the OP never asked about. This answer could be replaced with "use time.sleep()"

@Haran Rajkumar 2018-06-05 07:10:14

While everyone else has suggested the de facto time module, I thought I'd share a different method using matplotlib's pyplot function, pause.

An example

from matplotlib import pyplot as plt
plt.pause(5)    # Pauses the program for 5 seconds

Typically this is used to prevent the plot from disappearing as soon as it is plotted or to make crude animations.

This would save you an import if you already have matplotlib imported.

@Jan Vlcinsky 2014-05-14 21:30:35

A bit of fun with a sleepy generator.

The question is about time delay. It can be fixed time, but in some cases we might need a delay measured since last time. Here is one possible solution:

Delay measured since last time (waking up regularly)

The situation can be, we want to do something as regularly as possible and we do not want to bother with all the last_time, next_time stuff all around our code.

Buzzer generator

The following code (sleepy.py) defines a buzzergen generator:

import time
from itertools import count

def buzzergen(period):
    nexttime = time.time() + period
    for i in count():
        now = time.time()
        tosleep = nexttime - now
        if tosleep > 0:
            time.sleep(tosleep)
            nexttime += period
        else:
            nexttime = now + period
        yield i, nexttime

Invoking regular buzzergen

from sleepy import buzzergen
import time
buzzer = buzzergen(3) # Planning to wake up each 3 seconds
print time.time()
buzzer.next()
print time.time()
time.sleep(2)
buzzer.next()
print time.time()
time.sleep(5) # Sleeping a bit longer than usually
buzzer.next()
print time.time()
buzzer.next()
print time.time()

And running it we see:

1400102636.46
1400102639.46
1400102642.46
1400102647.47
1400102650.47

We can also use it directly in a loop:

import random
for ring in buzzergen(3):
    print "now", time.time()
    print "ring", ring
    time.sleep(random.choice([0, 2, 4, 6]))

And running it we might see:

now 1400102751.46
ring (0, 1400102754.461676)
now 1400102754.46
ring (1, 1400102757.461676)
now 1400102757.46
ring (2, 1400102760.461676)
now 1400102760.46
ring (3, 1400102763.461676)
now 1400102766.47
ring (4, 1400102769.47115)
now 1400102769.47
ring (5, 1400102772.47115)
now 1400102772.47
ring (6, 1400102775.47115)
now 1400102775.47
ring (7, 1400102778.47115)

As we see, this buzzer is not too rigid and allow us to catch up with regular sleepy intervals even if we oversleep and get out of regular schedule.

@Evan Fosmark 2009-02-04 07:05:59

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

@ssj 2014-04-25 08:14:32

if you need some conditions to happen. It better to user threading.Event.wait.

@Parthian Shot 2015-06-17 19:29:46

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 2017-08-03 10:41:35

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 2018-03-31 00:07:36

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 supports Monica 2018-04-10 08:57:36

@SDsolar What is wrong with sleep: You can't do any processing while it is sleeping, it basically puts the program on hold.

@SDsolar 2018-04-10 15:29:46

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.

@Peter Mortensen 2018-06-14 21:05:28

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?

@Boris 2019-05-21 20:13:47

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

Related Questions

Sponsored Content

16 Answered Questions

[SOLVED] What are metaclasses in Python?

63 Answered Questions

[SOLVED] Calling an external command from Python

26 Answered Questions

[SOLVED] How do I concatenate two lists in Python?

36 Answered Questions

[SOLVED] How to get the current time in Python

  • 2009-01-06 04:54:23
  • user46646
  • 3084725 View
  • 2626 Score
  • 36 Answer
  • Tags:   python datetime time

24 Answered Questions

[SOLVED] How do I parse a string to a float or int?

41 Answered Questions

[SOLVED] How do I merge two dictionaries in a single expression?

29 Answered Questions

[SOLVED] Finding the index of an item given a list containing it in Python

  • 2008-10-07 01:39:38
  • Eugene M
  • 3530968 View
  • 2894 Score
  • 29 Answer
  • Tags:   python list indexing

23 Answered Questions

[SOLVED] Does Python have a ternary conditional operator?

21 Answered Questions

[SOLVED] How do I list all files of a directory?

  • 2010-07-08 19:31:22
  • duhhunjonn
  • 3760779 View
  • 3474 Score
  • 21 Answer
  • Tags:   python directory

17 Answered Questions

[SOLVED] How to make a chain of function decorators?

Sponsored Content