dongxian1699 2017-10-25 21:01
浏览 433

Python 2.7中是否有类似于Go的time.Tick或Netty的HashedWheelTimer的东西?

I write a lot of code that relies on precise periodic method calls. I've been using Python's futures library to submit calls onto the runtime's thread pool and sleeping between calls in a loop:

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)

However, I've noticed that this implementation introduces some drift after a long duration of running (e.g. I've run this code for about 10 hours and noticed about 7 seconds of drift). For my work I need this to run on the exact second, and millisecond would be even better. Some folks have pointed me to asyncio ("Fire and forget" python async/await), but I have not been able to get this working in Python 2.7.

I'm not looking for a hack. What I really want is something akin to Go's time.Tick or Netty's HashedWheelTimer.

  • 写回答

1条回答 默认 最新

  • doumi1944 2017-10-25 21:24
    关注

    Nothing like that comes with Python. You'd need to manually adjust your sleep times to account for time spent working.

    You could fold that into an iterator, much like the channel of Go's time.Tick:

    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()
    

    Note that the above ticker starts ticking when you start iterating, rather than when you call tick, which matters if you try to start a ticker and save it for later. Also, it doesn't send the time, and it won't drop ticks if the receiver is slow. You can adjust all that on your own if you want.

    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?