I would like my Python2 daemon to wake up and do something exactly on the second.
Is there a better way to get the decmal part of a floating point number for a sleep time other then:
now = time.time() #get the current time in a floating point format
left_part = long(now) #isolate out the integer part
right_part = now - left_part #now get the decimal part
time.sleep(1 - right_part) #and sleep for the remaining portion of this second.
The sleep time will be variable depending on how much work was done in this second.
Is there a "Sleep till" function I don't know about? or, is there a better way to handle this?
I would like my daemon to be as efficient as possible so as not to monopolize too much CPU from other processes.
Thanks. Mark.
time.sleep
isn't guaranteed to wake up exactly when you tell it to, it can be somewhat inaccurate.
For getting the part after the decimal place, use the modulus (%
) operator:
>>> 3.5 % 1
.5
e.g.:
>>> t = time.time()
>>> t
1430963764.102048
>>> 1 - t % 1
0.8979520797729492
As for "sleep til", you might be interested in the sched module, which is built around that idea: https://docs.python.org/2/library/sched
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With