0

I use async create_task to run my task in background, but my_task() method not be executed.

async def my_task(): print("starting my task...") time.sleep(2) print("finished my task.") if __name__ == '__main__': print("1111") loop = asyncio.get_event_loop() loop.create_task(my_task()) print("2222") 

the result is

1111 2222 
5
  • 1
    It is not sufficient to call create_task(), you need to run the event loop, e.g. using loop.run_until_complete(my_task()). Also, you cannot call time.sleep() in an async function, you must await asyncio.sleep(2) instead. Commented May 24, 2021 at 9:56
  • @user4815162342: You can call time.sleep. You just really shouldn't, unless you're trying to simulate CPU-bound work that wouldn't await back to the event loop. Commented May 24, 2021 at 10:07
  • @ShadowRanger Such simulation is misguided because CPU work shouldn't be done in the asyncio thread either, as it will halt the executor. One should off-load such work to another thread or process using loop.run_in_executor(). Commented May 24, 2021 at 10:53
  • @user4815162342: Depends how much of it there is. I'll grant, a two second sleep is simulating entirely too much await-less CPU work. But a tenth of a second? Eh, that's within the bounds of reason. Commented May 24, 2021 at 12:48
  • @ShadowRanger Agreed. The "acceptable" amount of pause without yielding is a matter of some debate in the async world, but it boils down to how much latency it is acceptable to add to an arbitrary IO event that might arrive while the event loop is halted. If the CPU spikes are comparatively rare and the system doesn't have strict latency constraints, then even a 1s pause could be acceptable. Another thing to take into account is that Python has a stop-the-world GC that can have quite large pauses when under load. But I'm digressing... Commented May 24, 2021 at 13:20

1 Answer 1

1

There is a simple fix for this, but you still need to use await which you cannot avoid because create tasks returns a coroutine

import asyncio async def my_task(): print("starting my task...") await asyncio.sleep(2) print("finished my task.") if __name__ == '__main__': print("1111") loop = asyncio.get_event_loop() loop.run_until_complete(my_task()) # or use can use asyncio.run(my_task()) print("2222") 

EDIT: Made changes for pyfile, instead of notebook, thanks user4815162342 for pointing out

Sign up to request clarification or add additional context in comments.

2 Comments

await won't work at top-level, you must call asyncio.run() or loop.run_until_complete() instead.
Good point, i ran this with a notebook, with nest_asycnio.apply()

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.