SiteMap  | About    

Python time.sleep() Method

How can I make a time delay in Python?

Python sleep() method used to suspend the execution for given of time(in seconds). We can use python sleep function to halt the execution of the program for given time in seconds. The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal's catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system. You can set a delay in your Python script by passing the number of seconds you want to delay to the sleep function.

When you run the above example, it will end only after five seconds.

The sleep() method supports floating point numbers, meaning you can make it wait fractions of a second too.

When you run the above example, the program wait for 1 second and 500 milliseconds to finish.

  1. time.sleep(1) # sleep for 1 seconds
  2. time.sleep(60) # sleep for 1 minute
  3. time.sleep(3600) # sleep for 1 hour

Time delay for infinite loop

Here is another example where something is run approximately each 5 seconds.

The above program run an infinite loop, so you should forcefully stop the program when you want.

Count down program with sleep

The following program is a countdown example, using sleep method to wait 1 second each number.

Thread and Sleep

Threads are usually contained in processes. More than one thread can exist within the same process. These threads share the memory and the state of the process. From the following example you can see how sleep() method work in a multi treaded program.


Accuracy of time.sleep()

The time.sleep(seconds) is not real time. The time.sleep() function uses the underlying operating system's sleep() function, sometimes it may be off in terms of milliseconds. Most PC machines have hardware limits in the 1-10ms range, regardless of operating system. To the operating system, time.sleep() just means a hint. It's not a good timing mechanism, but good enough for most applications. Generally however, unless you want to sleep for a very small period, you can generally ignore this information.

output (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.