Python Forum
How to add coroutine to a running event loop?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to add coroutine to a running event loop?
#2
Don't use await until you want to stop adding things to the event loop. Whatever you want to be running together, add to the event loop, and then after they're all added is when you await the various tasks. Here's an example:

import asyncio

async def worker():
    print("Starting work")
    await asyncio.sleep(5)
    print("Work complete")

async def other_worker():
    print("Starting other worker")
    await asyncio.sleep(2)
    print("Other worker complete")

async def third_worker():
    print("Starting third worker")
    await asyncio.sleep(1)
    print("Third worker complete")

async def main():
    print("Starting workers")
    tasks = []
    tasks.append(asyncio.ensure_future(worker()))
    tasks.append(asyncio.ensure_future(other_worker()))

    print("First two workers added to the event loop.")
    for task in tasks:
        await task

    print("Adding third worker to the event loop.")
    await third_worker()
    # in this case, this is the same thing
    await asyncio.ensure_future(third_worker())

asyncio.run(main())
Output:
Starting workers First two workers added to the event loop. Starting work Starting other worker Other worker complete Work complete Adding third worker to the event loop. Starting third worker Third worker complete Starting third worker Third worker complete
Reply


Messages In This Thread
RE: How to add coroutine to a running event loop? - by nilamo - Mar-21-2019, 06:04 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Coroutine was never awaited error bucki 1 651 Sep-23-2023, 08:17 PM
Last Post: deanhystad
  help RuntimeError: no running event loop marpaslight 5 3,707 Oct-18-2022, 10:04 PM
Last Post: marpaslight
  A question about 'Event loop is closed' fc5igm 2 2,198 Oct-05-2021, 02:00 AM
Last Post: fc5igm
  bleak library RuntimeError: This event loop is already running alice93 3 4,077 Sep-30-2021, 08:06 AM
Last Post: alice93
  loop running indefinitely shantanu97 6 2,549 Sep-29-2021, 08:03 PM
Last Post: deanhystad
  Running A Loop Until You See A Particular Result knight2000 6 31,667 Sep-04-2021, 08:55 AM
Last Post: knight2000
  Running loop at specific frequency mdsousa 3 5,911 Apr-21-2021, 11:22 AM
Last Post: jefsummers
  RuntimeError: This event loop is already running newbie2019 2 6,950 Sep-30-2020, 06:59 PM
Last Post: forest44
  Running function from parent module which has a loop in it. ta2909i 1 2,683 Nov-18-2019, 07:04 PM
Last Post: Gribouillis
  How to get coroutine from a task, and an object from a coroutine? AlekseyPython 2 4,405 Mar-23-2019, 01:41 PM
Last Post: AlekseyPython

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020