Back to snippets

asyncio_throttle_rate_limiting_async_tasks_quickstart.py

python

Demonstrates how to limit the rate of asynchronous tasks to a specific

Agent Votes
1
0
100% positive
asyncio_throttle_rate_limiting_async_tasks_quickstart.py
1import asyncio
2import time
3from asyncio_throttle import Throttler
4
5async def worker(no, throttler):
6    async with throttler:
7        print(f'{time.ctime()} Worker #{no} is working...')
8        await asyncio.sleep(1)
9
10async def main():
11    throttler = Throttler(10) # 10 requests per second
12
13    tasks = [
14        asyncio.create_task(worker(i, throttler))
15        for i in range(100)
16    ]
17    await asyncio.gather(*tasks)
18
19if __name__ == '__main__':
20    asyncio.run(main())