Welcome, guest | Sign In | My Account | Store | Cart

time.sleep(delay) will sleep for, at most, delay seconds. This function will sleep for at least delay seconds.

Python, 12 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from time import time, sleep

def sleep_min(delay):
    accum = 0
    remainder = delay
    while accum < delay:
        begin = time()
        sleep(remainder)
        end = time()
        slept = end - begin
        accum += slept
        remainder -= slept

I've had to write this function so many times I can't count. The most recent time I wrote this was for a test that ensured that my long-polling request was indeed taking advantage of the long-polling feature in my server.

1 comment

Sunjay Varma 13 years ago  # | flag

time.sleep seems pretty reliable:

>>> def testsleep(t=2):
    s = time()
    sleep(t)
    return time() - s



>>> testsleep(10)
10.0
>>> testsleep(2)
2.0
>>> testsleep(300)
300.0
Created by Drew Vogel on Tue, 8 Feb 2011 (MIT)
Python recipes (4591)
Drew Vogel's recipes (1)

Required Modules

Other Information and Tasks