Pascal Jahan Elahi (Pawsey)
01/20/2025, 2:48 AMMarvin
01/20/2025, 2:48 AMasyncio
library, which supports asynchronous programming. Specifically, asyncio.wait
can be used to wait for one or more coroutines to complete.
Here's a basic pattern you can follow:
python
import asyncio
async def function_one():
# Simulate some work with a sleep
await asyncio.sleep(2)
return 'Function One Completed'
async def function_two():
# Simulate some work with a sleep
await asyncio.sleep(1)
return 'Function Two Completed'
async def main():
# Schedule the tasks
tasks = [function_one(), function_two()]
# Wait for the first task to complete
done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
# Process the results of the completed task
for task in done:
print(task.result())
# Optionally, cancel pending tasks if needed
for task in pending:
task.cancel()
# Run the main function
asyncio.run(main())
This example demonstrates how to wait for the first of two functions to complete using asyncio.wait
with the return_when=asyncio.FIRST_COMPLETED
parameter. This approach is useful when you're working with Prefect's asynchronous tasks, which follow standard async Python behavior.
For more on asynchronous functions in Prefect, you can check out their documentation on writing tasks.