我写了很多依赖于精确周期方法调用的代码。我一直在使用Python的futures
库将调用提交到运行时的线程池中,并在循环中在调用之间进行睡眠:
executor = ThreadPoolExecutor(max_workers=cpu_count())
def remote_call():
# make a synchronous bunch of HTTP requests
def loop():
while True:
# do work here
executor.submit(remote_call)
time.sleep(60*5)
然而,我注意到这种实现在长时间运行后会引入一些漂移(例如,我已经运行了这段代码约10个小时,发现漂移了约7秒)。对于我的工作,我需要它在准确的秒数上运行,毫秒甚至更好。有些人指向了
asyncio
("Fire and forget" python async/await),但我无法在Python 2.7中使其工作。我不想要任何黑客行为。我真正想要的是类似于Go的
time.Tick
或Netty的 HashedWheelTimer
。
_PyTime_GetMonotonicClock()
来获取时间。不幸的是,无论Python 2的time.sleep
是否单调,我都不认为Python 2在任何地方公开了一个平台无关的单调时钟。(Python 3有time.monotonic
。) - user2357112