Python2.7中是否有类似于Go';s`time.Tick`或Netty';“HashedWheelTimer”?

Python2.7中是否有类似于Go';s`time.Tick`或Netty';“HashedWheelTimer”?,python,python-2.7,go,python-asyncio,concurrent.futures,Python,Python 2.7,Go,Python Asyncio,Concurrent.futures,我编写了很多依赖于精确周期方法调用的代码。我一直在使用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

我编写了很多依赖于精确周期方法调用的代码。我一直在使用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
(),但我无法在Python2.7中实现这一点


我不是在找黑客。我真正想要的是类似Go的
时间。勾选
或Netty的
HashedWheelTimer

Python没有类似的功能。你需要手动调整你的睡眠时间来计算工作时间

您可以将其折叠成迭代器,就像Go的
时间频道一样。勾选

import itertools
import time
import timeit

def tick(interval, initial_wait=False):
    # time.perf_counter would probably be more appropriate on Python 3
    start = timeit.default_timer()

    if not initial_wait:
        # yield immediately instead of sleeping
        yield

    for i in itertools.count(1):
        time.sleep(start + i*interval - timeit.default_timer())
        yield

for _ in tick(300):
    # Will execute every 5 minutes, accounting for time spent in the loop body.
    do_stuff()

请注意,当您开始迭代时,上面的ticker开始滴答作响,而不是在调用
tick
时,如果您尝试启动一个ticker并将其保存以备以后使用,则这一点很重要。而且,它不会发送时间,如果接收器速度慢,它也不会滴答声。如果你愿意,你可以自己调整所有这些。

可能是一个有趣的复制品(一些操作系统的图表):不是,一个复制品。尽管这告诉@nmurthy:我认为Python 3的信息已经过时了,尽管我不知道Python 2,而且我还没有在Python 2或Python 3上运行实验-我只是检查了源代码,发现Python 3正在使用
\u PyTime\u getmonotoniccold()
来获取时间。不幸的是,无论Python2
time.sleep
是否是单调的,我认为Python2都不会在任何地方公开平台无关的单调时钟。(Python 3有
时间。单调的