zonk
zonk

Reputation: 167

Manage asyncio coroutines in dict

I want to manage some coroutines in a dict, while running a main coroutine. Specifically I want to start endless coroutines, put the handler of them in a dict and cancel them via a dict call again. In my example I want to start 4 Coroutines and they shall cancel one by one again with the coroutine doomsday. I'm using Python 3.6.

import asyncio
import traceback


async def add_to_handler(node, func):
    func_handler[node] = asyncio.ensure_future(func, loop=loop)
    return

async def test_func1():
    while True:
        print("1 - HeNlO")
        await asyncio.sleep(1)

async def test_func2():
    while True:
        print("2 - TestFunc2")
        await asyncio.sleep(2)


async def test_func3():
    while True:
        print("3 - Tukan")
        await asyncio.sleep(3)


async def test_func4():
    while True:
        print("4 - Do Coro!")
        await asyncio.sleep(4)


async def doomsday():
    # Cancel coroutine every 10 seconds
    print("launch doomsday")
    for i in range(len(func_handler)):
        await asyncio.sleep(10)
        print("start cancelling with {}".format(i))
        func_handler[str(i + 1)].cancel()
    return

async def main():
    await add_to_handler("1", test_func1)
    await add_to_handler("2", test_func2)
    await add_to_handler("3", test_func3)
    await add_to_handler("4", test_func4)
    await doomsday()
    while True:
        print("z..z..Z..Z...Z")
        print(func_handler)
        await asyncio.sleep(5)

func_handler = {}

loop = asyncio.get_event_loop()
try:
    loop.run_until_complete(main())
except KeyboardInterrupt:
    print("stop loop")
    loop.close()

I tried it with the .call_latermethod of AbstractEventLoop instead of an endless while loop, but it still doesn't want to work and it seems, that my coroutines are seen as function, but I don't know why. Where is my fault?

Upvotes: 1

Views: 1237

Answers (1)

IVI
IVI

Reputation: 149

try to change this function:

async def add_to_handler(node, func):
    func_handler[node] = asyncio.ensure_future(func(), loop=loop)
    return None

pay attention on asyncio.ensure_future(func(),loop=loop)

Upvotes: 2

Related Questions