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
create_task(), you need to run the event loop, e.g. usingloop.run_until_complete(my_task()). Also, you cannot calltime.sleep()in an async function, you mustawait asyncio.sleep(2)instead.time.sleep. You just really shouldn't, unless you're trying to simulate CPU-bound work that wouldn'tawaitback to the event loop.loop.run_in_executor().await-less CPU work. But a tenth of a second? Eh, that's within the bounds of reason.