asyncio Python的节流器,节流到下一整秒钟
aio-throttle-to-next-second的Python项目详细描述
aio节流到下一秒
asyncio Python的节流器,它将节流到下一秒,如time.time()
报告的那样。这对于对使用“最新时间戳获胜”策略(如S3)的服务的请求强制排序非常有用。
安装
pip install aio-throttle-to-next-second
使用
创建一个没有参数的共享Throttler
然后,就在要被限制的代码段之前,调用这个和await
它的结果。
awaitthrottler()# Each execution reaching this line will reach this line at a different second
示例:多个任务被限制
importasyncioimporttimefromaio_throttle_to_next_secondimportThrottlerasyncdefmain():throttler=Throttler()awaitasyncio.gather(*[worker(throttler)for_inrange(10)])asyncdefworker(throttler):awaitthrottler()# Each print will show a distinct second, though all workers started togetherprint(int(time.time()))loop=asyncio.get_event_loop()loop.run_until_complete(main())loop.close()
示例:单个任务被限制
importasyncioimportrandomimporttimefromaio_throttle_to_next_secondimportThrottlerasyncdefmain():throttler=Throttler()for_inrange(10):awaitthrottler()# Each print will show a distinct second, though there is a random sleepprint(int(time.time()))awaitasyncio.sleep(random.random())loop=asyncio.get_event_loop()loop.run_until_complete(main())loop.close()
- 项目
标签: