9

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.

Shaddi
  • 313
  • 1
  • 3
  • 8

7 Answers7

12

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
  • 6,888
  • 3
  • 21
  • 17
  • 1
    +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 Dec 21 '09 at 19:10
8

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
  • 307,395
  • 66
  • 306
  • 293
7

This changed in version 3.5:

time.sleep(*secs*): The function now sleeps at least secs even if the sleep is interrupted by a signal, except if the signal handler raises an exception (see PEP 475 for the rationale)

Umutambyi Gad
  • 4,082
  • 3
  • 18
  • 39
Mat
  • 111
  • 1
  • 3
6

Actual answer, at least for my machine: 4294967.2950000003911900999... seconds.

sleep(4294967.2950000003911901)

OverflowError: sleep length is too large

Matt
  • 89
  • 1
  • 1
1

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
  • 1,482
  • 1
  • 15
  • 21
1

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
  • 19,175
  • 11
  • 72
  • 80
  • 1
    This is a bit better, but it still might sleep for less than n if the sleep() calls are getting interrupted early. – samtregar Dec 21 '09 at 18:14
  • 1
    well, in this case, i's change the function to: t0 = time.time(); while time.time() < t0 + n: sleep(1) – mykhal Dec 21 '09 at 18:49
0

I've also encountered a situation where i had to Question myself this. in my case my thread would need to sleep like for a long time (days, months). As matt Answered with an interesting fact that there is a limit. in his and my system the limit is 4.29Million secs + and different System has different limits as Someone In mats answer's comment said Repl.it has bigger limit.

So anyways, after all we are limited to it but i found a solution to that which is to divide seconds into chunks with a max_sleep_secs and then looping through that chunks list and sleep.

import time


def sweet_dreams(secs: float):
    DEBUG = False
    max_sleep_secs = 1000000
    secs_extra_ms = 0

    if secs > max_sleep_secs:
        if type(secs) is float:
            secs_extra_ms = str(secs).split('.')[-1]
            if secs_extra_ms:
                secs_extra_ms = secs_extra_ms.lstrip('0')

            secs_extra_ms = float(f"0.{secs_extra_ms}")

        secs = int(secs)
        secs_divide = float(secs) / max_sleep_secs  # e.g: 2.4123
        secs_int = int(secs_divide)  # e.g: 2
        secs_decimal_remainder = int(str(secs_divide).split(".")[-1])  # e.g 4123
        chunks = [max_sleep_secs for _ in range(secs_int)]
        if secs_decimal_remainder:
            chunks.append(int(str(secs_decimal_remainder).lstrip('0')))

        if secs_extra_ms:
            chunks.append(secs_extra_ms)

        if DEBUG:
            print(f"Debug [sweet_dreams]: -> Total: {secs} | Max: {max_sleep_secs} | Chunks: {chunks}")
            quit()

        for seconds in chunks:
            time.sleep(seconds)
    else:
        if DEBUG:
            print(f"Debug [sweet_dreams]: -> Total: {secs} | Max: {max_sleep_secs} | Chunks: None")
            quit()

        time.sleep(secs)