Package brisa :: Package utils :: Module safe_sleep
[hide private]
[frames] | no frames]

Source Code for Module brisa.utils.safe_sleep

 1  # Licensed under the MIT license 
 2  # http://opensource.org/licenses/mit-license.php or see LICENSE file. 
 3  # Copyright 2007-2008 Brisa Team <brisa-develop@garage.maemo.org> 
 4   
 5  """ Provides a way of sleeping safely. 
 6  """ 
 7   
 8  from time import sleep as systemsleep 
 9  from time import time 
10  import select 
11  from brisa.core import log 
12   
13   
14 -def tsleep(timeout, death_fd):
15 if death_fd: 16 # Interruptable sleep 17 read, dummy1, dummy2 = select.select([death_fd], [], [], timeout) 18 if read: 19 return False 20 else: 21 systemsleep(timeout) 22 return True
23 24
25 -def safe_sleep(t, death_fd=None):
26 """ Implementation of a simple smart sleep function. This function makes 27 sure the whole sleep time is slept properly. 28 29 @param t: sleep time 30 @type t: integer 31 """ 32 if t < 1: 33 # We don't need this precision for sleeping. time.sleep() gives almost 34 # two decimal points of precision in sleeping 35 return tsleep(t, death_fd) 36 37 remaining = t 38 39 # For an interval of 1600 seconds, the rate will be 1600/10.0 = 160 s. 40 # For an interval of 10 seconds, the rate will be 10/10 = 1 second. 41 rate = t / 10.0 42 43 # Precision of 0.001. For example, if we have an interval of 1600 s, 44 # then the precision will be 1600/1000 = 1.6 seconds. 45 # For an interval of 10 seconds, the precision will be 10/1000 = 0.01 s. 46 precision = t / 1000.0 47 initial = time() 48 49 # If remaining is in the interval (0, precision), then leave 50 while remaining > precision: 51 # Measure the interval (t0, t1) and estimate the remaining 52 t0 = time() 53 54 if rate < remaining: 55 if not tsleep(rate, death_fd): 56 return False 57 else: 58 # If rate is bigger than the remaining time, then just sleep the 59 # remaining. We don't want to sleep more than the interval. 60 if remaining > 0: 61 if not tsleep(remaining, death_fd): 62 return False 63 else: 64 # If negative, already slept too much, so, set it to zero 65 remaining = 0 66 67 t1 = time() 68 69 remaining -= (t1-t0) 70 71 final = time() 72 return True
73