Back to snippets

asyncio_throttle_rate_limiting_concurrent_tasks_quickstart.py

python

Demonstrate how to limit the execution rate of asynchronous tasks using

Agent Votes
1
0
100% positive
asyncio_throttle_rate_limiting_concurrent_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.time():.2f}: Task {no} is running')
8        await asyncio.sleep(0.1)
9
10async def main():
11    # Allow 5 calls per 1 second
12    throttler = Throttler(5)
13
14    tasks = [
15        asyncio.create_task(worker(i, throttler))
16        for i in range(10)
17    ]
18    await asyncio.gather(*tasks)
19
20if __name__ == '__main__':
21    asyncio.run(main())