Python Forum
How to manage a dynamic list of tasks with asyncio
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to manage a dynamic list of tasks with asyncio
I have a main class which creates an instance from a list of plugins. In the example below, the 'dhcpv6' plugin is launched and it listens for subscriptions on the 'subject_test_subscribe" subject. As soon as the handler intercepts a new message on this subject, it creates an new asynchronous task by instantiating the classe "Dhcpv6_child().run()" which represents a child of the class Each child have a timeout to kill the process child. For information, the class plugin definied in is an abstract class which allows to load plugins.

I'm not able to dynamically manage the addition of new tasks with asyncio.gather (until the current task is finished, the new task is not executed). The problem is solved with asyncio.create_subprocess_exec but I'd prefer to use the possibilities of asyncio
import argparse
import asyncio
import importlib

parser = argparse.ArgumentParser()
parser.add_argument('--nats', '-n', nargs="?", type=str, required=True, help="adresse IP du serveur NATS")
parser.add_argument('--plugins', '-p', nargs="+", help="Liste de plugins a utiliser")
args = parser.parse_args()

print("************** main() *****************")
print(f"NATS server IP: {args.nats}")
print(f"List of plugins to load: {args.plugins}")

async def main():
    tasks = []
    for type_plugin in args.plugins:
            module = importlib.import_module(f'Plugins.{type_plugin}')
            my_class = getattr(module, type_plugin)
            my_instance = my_class(nats=args.nats)
        except Exception as e:
            print("Erreur chargement du plugin : ", type_plugin, ":",  e)

        await asyncio.gather(*tasks)
    except asyncio.TimeoutError:
        print("timeout main")

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    except KeyboardInterrupt:
    except Exception as e:
import asyncio
import json
import logging
import sys

from nats.aio.client import Client as NATS
from nats.aio.errors import ErrConnectionClosed, ErrTimeout, ErrNoServers
from Plugins import Plugin
from Plugins.Dhcpv6_child import Dhcpv6_child

logger = logging.getLogger("dhcpv6")

class Dhcpv6(Plugin):
    name = "Dhcpv6 plugin"
    subject = "subject_test_subscribe"

    def __init__(self, **kwargs):
        self.nats = kwargs.get('nats')
        self.list_task = []
        self.timeout_task = 5
        print("Class dhcpv6 ==> constructor /  nats_ip : {}".format(self.nats))

    async def run(self):
        print("******* run DHCPV6 ***********")
        nc = NATS()
            await nc.connect("", verbose=True, pedantic=True)
        except ErrConnectionClosed:
            print(f"La connexion a ete fermee inopinement")
        except ErrTimeout:
            print(f"Le delai imparti a la connexion est depasse")
        except ErrNoServers:
            print(f"Aucun serveur n'a repondu a temps")
        except Exception as e:
            print(f"Exception inattendue: {e}")

        async def plugin_handler(msg):
                # Creating and running a new task on demand
                    asyncio.create_task(Dhcpv6_child().run()), timeout=self.timeout_task))
                print("append a new task : ", self.list_task)
                print("Error append new task")

                print("Running a new task : ", self.list_task)
                await asyncio.wait_for(asyncio.gather(*self.list_task), timeout=3600.0)
            except asyncio.TimeoutError:
                print("Fin du main : timeout atteint")

        print(f"Subscribing test on : {self.subject}")
        await nc.subscribe(f"{self.subject}", cb=plugin_handler)

        while nc.is_connected:
            await asyncio.sleep(0.5)
        await nc.drain()
Output screen example :
************** main() *****************
NATS server IP:
List of plugins to load: : ['Dhcpv6']

------------ Load a list of plugins : {Dhcpv6} -------
Class plugin ==> constructor
Class dhcpv6 ==> constructor /  nats_ip :

******* run DHCPV6 ***********
INFO:Plugin:Plugin Dhcpv6 plugin loaded
Subscribing test on : subject_test_subscribe
<Msg: subject='subject_test_subscribe' reply='' data='{"query": ...'>

Class CHILD ==> constructor
append a new task :  [<coroutine object wait_for at 0x0000026D0310F040>]
Runnig a new task :  [<coroutine object wait_for at 0x0000026D0310F040>]

Possibly Related Threads…
Thread Author Replies Views Last Post
  Starlette: accumulated tasks. Why? lifemaker 2 496 Jul-07-2021, 10:15 AM
Last Post: lifemaker

Forum Jump:

User Panel Messages

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