How to add new co-routine to already running loop in Python asyncio?

wisnshaftler

I wrote a code like this.

import asyncio
import time
import random

async def secondCoro(myId):
    waiting_time = random.randint(1,5)
    while 1:
        print("i am {} ".format(myId))
        time.sleep(waiting_time)


async def main():
    for i in range (10):
        await loop.create_task(secondCoro(i))
        time.sleep(0.1)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

I need to run 10 coroutines at the same time. I gave random sleep time so I think it will be show output like this.

i am 0

i am 2

i am 4

i am 1

i am 2

i am 8

i am 5

But when I run this code it only shows,

i am 0

i am 0

i am 0

Is this achievable? If yes what is problem in my code and how do I fix this? If there are no errors, are there any possible ways to run many co-routines?

user4815162342

There are two issues with your code:

  • async code must not block, so instead of calling time.sleep(), you must await asyncio.sleep().

  • "await" means "wait until done", so when you await the tasks in your loop in main(), you never get past the first iteration of the loop because the task never finishes.

There are several ways to fix the second issue. For example, you can call asyncio.gather(), or you can keep the loop as-is, but omit the awaiting of the tasks, and instead await them in a second loop. For example:

async def secondCoro(myId):
    waiting_time = random.randint(1,5)
    while True:
        print("i am {} ".format(myId))
        await asyncio.sleep(waiting_time)

async def main():
    # start all the tasks
    tasks = [asyncio.create_task(secondCoro(i)) for i in range(10)]
    # and await them, which will basically wait forever, while still
    # allowing all the tasks to run
    for t in tasks:
        await t

asyncio.run(main())

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

How can I add to a already running process an additional 'shutdown' command?

分類Dev

how to add a coroutine to running event loop?

分類Dev

How to check the process is already running or not

分類Dev

How to add date column to already existing time column in python?

分類Dev

How to add new string between a string python

分類Dev

How does asyncio (python) work?

分類Dev

how to keep running the loop in python even after a KeyError

分類Dev

how to configure already running cluster in kubernetes

分類Dev

How can I add a new data partition on Mac with splitting the main partition in two parts? Windows 7 is already installed with bootcamp

分類Dev

How do I add tasks to a Tokio event loop that is running on another thread?

分類Dev

How to terminate a running loop in java?

分類Dev

How to wrap custom future to use with asyncio in Python?

分類Dev

how to iterate over multiple dataframes and add values to new dataframe in python

分類Dev

How to prevent raise asyncio.TimeoutError and continue the loop

分類Dev

python asyncio add_done_callback with async def

分類Dev

Flutter how to get firebase dynamic link if app is already running?

分類Dev

Python Kivy: Add Background loop

分類Dev

How to use groupby().apply() instead of running loop on whole dataset in Python Pandas?

分類Dev

Attach to already running JVM

分類Dev

Cancelling a already running task

分類Dev

JMockit: How to override already mocked method with a new mock?

分類Dev

Add Dropbox SDK to my app already running Chooser API, and is live on store

分類Dev

How to add new line in a file

分類Dev

how to add an new object with lists in it

分類Dev

How to add XElements dynamically in a loop?

分類Dev

Unable to return from infinite loop inside routine

分類Dev

Python AsyncIOのloop.add_reader()はどのファイル記述子オブジェクトを期待しますか?

分類Dev

Python3 how to asyncio.gather() a list of partial functions

分類Dev

Submit a job to an asyncio event loop

Related 関連記事

  1. 1

    How can I add to a already running process an additional 'shutdown' command?

  2. 2

    how to add a coroutine to running event loop?

  3. 3

    How to check the process is already running or not

  4. 4

    How to add date column to already existing time column in python?

  5. 5

    How to add new string between a string python

  6. 6

    How does asyncio (python) work?

  7. 7

    how to keep running the loop in python even after a KeyError

  8. 8

    how to configure already running cluster in kubernetes

  9. 9

    How can I add a new data partition on Mac with splitting the main partition in two parts? Windows 7 is already installed with bootcamp

  10. 10

    How do I add tasks to a Tokio event loop that is running on another thread?

  11. 11

    How to terminate a running loop in java?

  12. 12

    How to wrap custom future to use with asyncio in Python?

  13. 13

    how to iterate over multiple dataframes and add values to new dataframe in python

  14. 14

    How to prevent raise asyncio.TimeoutError and continue the loop

  15. 15

    python asyncio add_done_callback with async def

  16. 16

    Flutter how to get firebase dynamic link if app is already running?

  17. 17

    Python Kivy: Add Background loop

  18. 18

    How to use groupby().apply() instead of running loop on whole dataset in Python Pandas?

  19. 19

    Attach to already running JVM

  20. 20

    Cancelling a already running task

  21. 21

    JMockit: How to override already mocked method with a new mock?

  22. 22

    Add Dropbox SDK to my app already running Chooser API, and is live on store

  23. 23

    How to add new line in a file

  24. 24

    how to add an new object with lists in it

  25. 25

    How to add XElements dynamically in a loop?

  26. 26

    Unable to return from infinite loop inside routine

  27. 27

    Python AsyncIOのloop.add_reader()はどのファイル記述子オブジェクトを期待しますか?

  28. 28

    Python3 how to asyncio.gather() a list of partial functions

  29. 29

    Submit a job to an asyncio event loop

ホットタグ

アーカイブ