Unclear about python async task cancel/shutdown at program exit

57 views Asked by At

I can't find docs that clearly describe the mechanism here so just want to try to understand and learn best practices. For tasks created by asyncio.create_task, they seem to be cleaned up at program end without generating any CancelledError or requiring a call to explicitly cancel the task. Do we need to cancel to ensure orderly shutdown, or does the asyncio loop stuff just handle all this cleanly for us?

Here's an example. The program seems to exit cleanly after 20s. So I'm assuming this idiom is fine. Just want to verify I'm not violating any best practices.

import asyncio
import random
import time


async def forever_while_loop_task():
    while True:
        sleep_seconds = random.randint(5, 30)
        print(f'sleeping for {sleep_seconds} seconds')
        await asyncio.sleep(sleep_seconds)
        print('looping')


async def main():
    start = time.monotonic()
    the_looping_task = asyncio.create_task(forever_while_loop_task())
    await asyncio.sleep(20)
    print(f'ok done with program, took {time.monotonic() - start:.2f}s')

    # Do I need to call the_looping_task.cancel() here 
    # or do anything to ensure orderly shutdown/cleanup?


if __name__ == "__main__":
    asyncio.run(main())

Sample output from a run:

sleeping for 12 seconds
looping
sleeping for 27 seconds
ok done with program, took 20.00s
0

There are 0 answers