There are three different scenarios you've posed:
- No
await statements (comment-out both) - Use only
await task1 (comment-out the second) - Use only
await task2 (commment-out the first)
Here's your script; extend the sleep time on task2 a bit just for illustration's sake.
# tasktest.py import time import asyncio async def say_after(delay, what): await asyncio.sleep(delay) print(what) async def main(): task1 = asyncio.create_task( say_after(1, 'hello')) task2 = asyncio.create_task( say_after(3, 'world')) print('started at', time.strftime('%X')) await task1 # await task2 print('finished at', time.strftime('%X')) asyncio.run(main())
1. No await statements
Here's the meat of asyncio.run():
loop = events.new_event_loop() try: events.set_event_loop(loop) loop.set_debug(debug) return loop.run_until_complete(main) # < ----- finally: try: _cancel_all_tasks(loop) # < ----- loop.run_until_complete(loop.shutdown_asyncgens()) finally: events.set_event_loop(None) loop.close()
Importantly, the loop only cares that main() is complete, and then cancels all other tasks that are associated with the running event loop. (Each task is tied to an event loop when it is specified.)
If you define main() without any await statements, create_task() schedules the tasks to be executed, but main() does not wait for either one of them to complete.
2. await task1
Setup:
await task1 # await task2
Output:
(base_py37) $ python3 tasktest.py started at 11:06:46 hello finished at 11:06:47
Both tasks move from pending to running, but only task1 completes, because main() only awaited on a task that takes ~1 second, not long enough for task2 to run.* (Notice that main() takes only 1 second.)
3. await task2
Setup:
# await task1 await task2
Output:
(base_py37) $ python3 tasktest.py started at 11:08:37 hello world finished at 11:08:40
Both tasks move from pending to running, and now both task1 and task2 complete, because main() awaited on a task that takes ~3 seconds, long enough for both tasks to run to completion.
*This applies at least to my setup (Mac OSX, ...) but as mentioned in the other answer here, the timing may play out differently on another setup and, if the task run-times are similar, both may get to run in places like case # 2.
await task2is commented out, i dont get any cancellation. I am using python 3.7 on windowsawaitcan lead to both tasks being run.