简体   繁体   中英

Asyncio does not run task scheduled through any of the many possible means

Here is what my base code looks like

def heavylifting(self):
  # Do the heavy lifting
  print('Done!')

async def async_heavylifting(self):
  await self.heavylifting()

Here are the various ways that fail to work:

Example1 - Nothing happens.

def do_the_things(self):
  loop = asyncio.new_event_loop()
  asyncio.set_event_loop(loop)
  asyncio.run_coroutine_threadsafe(self.async_heavylifting(), loop)

Example2 - This throws a no event loop error

def do_the_things(self):
  loop = asyncio.new_event_loop()
  asyncio.set_event_loop(loop)
  asyncio.create_task(self.async_heavylifting())

Example3 - Nothing happens

def do_the_things(self):
  loop = asyncio.new_event_loop()
  asyncio.set_event_loop(loop)
  loop.create_task(self.async_heavylifting())

Example4 - Not fire-and-forget. Blocks on heavylifting call

def do_the_things(self):
  loop = asyncio.new_event_loop()
  asyncio.set_event_loop(loop)
  loop.run_in_executor(None, self.heavylifting())

What am I doing wrong? How do I get my function to run?

Note - I want to achieve the fire-and-forget when I call my heavylifting function. I do not want to wait for it to finish

Your examples fail because you didn't START the event loop. There are several ways to do that, the simplest being:

asyncio.run(coro)

which will create the event loop, run the coroutine, and return the result.

Other methods are:

loop.run_until_complete(future)

An event loop method. It starts the loop and stops it again when the future is complete.

loop.run_forever()

Another event loop method. Starts the event loop. It will continue until loop.stop() is called.

Obtaining the event loop and starting it are two different steps. In my experience, the function call set_event_loop is only needed if you are running loops in multiple threads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM