views:

257

answers:

5

Is there an upper limit to how long you can specify a thread to sleep with time.sleep()? I have been having issues with sleeping my script for long periods (i.e., over 1k seconds). This issue has appeared on both Windows and Unix platforms.

+1  A: 

The spec says:

Suspend execution for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time. 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.

Nothing about a time limit here. Certainly 1K seconds isn't much and should work without problems.

Eli Bendersky
+5  A: 

I suppose the longer the time the more probable situation described in the docs:

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.

SilentGhost
Boldewyn
@Boldewyn: only because my firefox froze was I 3 seconds later then eli.
SilentGhost
@Boldewyn: we do provide different assessments, however.
SilentGhost
A: 

According to the documentation, time.sleep accepts any non-zero number [1], as you probably know. However you are under the influence of your operating systems scheduler as well [1].

[1] http://docs.python.org/library/time.html

zpon
Sorry, didn't see the other answers before posting.
zpon
A: 

you can prevent possible issues by putting the sleep with short delay into the loop:

def sleep(n):
    for i in xrange(n):
        time.sleep(1)
mykhal
This is a bit better, but it still might sleep for less than n if the sleep() calls are getting interrupted early.
samtregar
well, in this case, i's change the function to: t0 = time.time(); while time.time() < t0 + n: sleep(1)
mykhal
+3  A: 

Others have explained why you might sleep for less than you asked for, but didn't show you how to deal with this. If you need to make sure you sleep for at least n seconds you can use code like:

from time import time, sleep
def trusty_sleep(n):
    start = time()
    while (time() - start < n):
        sleep(n - (time() - start))

This may sleep more than n but it will never return before sleeping at least n seconds.

samtregar
+1 for not making the same mistake @mykhal does, where the cumulative effect of sleeping in small increments will build up to result in a noticeably greater total sleep than desired.
Peter Hansen