Relative Content

Tag Archive for python-asyncio

Asyncio: batched queue processor

I am trying to build a batched queue processor with asyncio. The way it should work is that one should be able to push individual requests into the queue and that the queue processor would batch these up based on some heuristic, process the batch and that it would then release the results back to the calling tasks. That each calling task should be blocked/awaited until it’s result is available.

How to yield control back to the event loop

import asyncio async def long_running_task(): try: while True: # Your long-running processing if asyncio.current_task().cancelled(): raise asyncio.CancelledError except asyncio.CancelledError: print(“Task was cancelled”) async def main(): task = asyncio.create_task(long_running_task()) await asyncio.sleep(5) # Let the task run for 5 seconds task.cancel() # Cancel the task print(“cancelled”) asyncio.run(main()) task.cancel() never gets called because it is single threaded and long_running_task() […]