Long Sleeps In Python
July 15, 2009 by Isaac
There is a portion of my test infrastructure that requires long sleep periods for stability soak testing purposes. So far the longest stability test run was 9 days. Originally, I simply used the time.sleep() method from the Python library. However, and I attribute this to VMware, I found that extremely inaccurate for long sleep durations. My test controller is running in a VM and although I have nothing to confirm this I suspect that VMware is doing funny stuff under the covers with the OS timer and that is throwing off the accuracy of time.sleep(). Anyway, here is my solution to the problem.
import time from datetime import datetime, timedelta def longsleep(minutes): """ The normal time.sleep() method is not very accurate from inside VMware when sleeping for long periods of time. This method is accurate to within +/- 5 seconds of the desired sleep time period. For long periods on the order of hours or days this small inaccuracy is acceptable. """ sleepTimeSec = 60 * minutes now = datetime.utcnow() td = timedelta(seconds=sleepTimeSec) endTime = now + td while now <= endTime: time.sleep(5) now = datetime.utcnow()
The method is accurate to around +/- 5 seconds, but for really long sleep durations 5 seconds is no big deal.
Posted in 
content rss
