Sobes.tech
Junior — Senior

Dynamic Asynchronous Task Scheduler

livecode

Task condition

It is necessary to build an asynchronous dispatcher that allows adding new coroutines in real-time with specified delays for their execution. The dispatcher should properly manage task launching, record their completion, and provide a mechanism to wait for the completion of both already running and newly added tasks.

import asyncio
import random
from typing import Callable, Coroutine, Any

class AsyncTaskScheduler:
    async def add_task(self, task_func: Callable[[], Coroutine[Any, Any, Any]]) -> asyncio.Task:
        """
        Adds a new task to the scheduler.

        :param task_func: Coroutine to be executed
        :return: asyncio.Task object
        """
        pass

    async def wait_for_all_tasks(self):
        """
        Waits for the completion of all current and future tasks.
        """
        pass

async def example_task(task_id: int, duration: float):
    """
    Example task with variable execution duration.

    :param task_id: Unique task identifier
    :param duration: Duration of the task
    """
    print(f"Task {task_id} started")
    await asyncio.sleep(duration)
    print(f"Task {task_id} completed after {duration} seconds")
    return task_id

async def main():
    pass

if __name__ == "__main__":
    asyncio.run(main())