Пример #1
0
async def stop_supervisor(supervisor_task: asyncio.Task, logger: Logger):
    if not supervisor_task.done():
        supervisor_task.cancel()

        done, _ = await asyncio.wait([supervisor_task])

    if not supervisor_task.done():
        logger.warning("unable to stop")
    else:
        if not supervisor_task.cancelled():
            exc = supervisor_task.exception()
            if exc is not None:
                logger.exception('exception thrown on stop: %s',
                                 exc,
                                 exc_info=exc)
Пример #2
0
async def cancel(task: asyncio.Task):
    if not (task.done() or task.cancelled()):
        try:
            task.cancel()
            await task
        except asyncio.CancelledError:
            pass
Пример #3
0
async def _update_codeblock(cb: ExpandingCodeblock,
                            task: asyncio.Task,
                            wait: float = 0.1):
    while not task.done():
        await cb.update_messages()
        await asyncio.sleep(wait)
    await cb.update_messages()
Пример #4
0
 async def infinite_chat_action(tracked_task: asyncio.Task) -> None:
     while True:
         if tracked_task.done():
             break
         else:
             await self.send_chat_action(chat_id=chat_id, action=action)
             await asyncio.sleep(delay)
Пример #5
0
    async def _async_run_long_action(self, long_task: asyncio.Task) -> None:
        """Run a long task while monitoring for stop request."""
        async def async_cancel_long_task() -> None:
            # Stop long task and wait for it to finish.
            long_task.cancel()
            with suppress(Exception):
                await long_task

        # Wait for long task while monitoring for a stop request.
        stop_task = self._hass.async_create_task(self._stop.wait())
        try:
            await asyncio.wait({long_task, stop_task},
                               return_when=asyncio.FIRST_COMPLETED)
        # If our task is cancelled, then cancel long task, too. Note that if long task
        # is cancelled otherwise the CancelledError exception will not be raised to
        # here due to the call to asyncio.wait(). Rather we'll check for that below.
        except asyncio.CancelledError:
            await async_cancel_long_task()
            raise
        finally:
            stop_task.cancel()

        if long_task.cancelled():
            raise asyncio.CancelledError
        if long_task.done():
            # Propagate any exceptions that occurred.
            long_task.result()
        else:
            # Stopped before long task completed, so cancel it.
            await async_cancel_long_task()
Пример #6
0
 def check_task_exception(self, fut: asyncio.Task):
     if fut.done():
         try:
             exc = fut.exception()
         except asyncio.CancelledError as e:
             exc = e
         if exc:
             self.log(f"Task raised exception: {str(exc)}")
async def ensureTaskCanceled(asyncio_task: asyncio.Task) -> None:
    while not asyncio_task.done():
        try:
            asyncio_task.cancel()
        except:
            pass
        finally:
            await asyncio.sleep(0)
Пример #8
0
        def on_timeout(task: asyncio.Task, loop: asyncio.AbstractEventLoop):
            nonlocal cancelled

            if task.done():
                return

            task.cancel()
            cancelled = True
Пример #9
0
 def is_done(task: asyncio.Task):
     if task.done():
         try:
             result = task.result()
             print(result.content)
         except:
             pass
         return True
     return False
Пример #10
0
def task_exc_info(task: asyncio.Task):
    """Extract exception info from an asyncio task."""
    if not task or not task.done():
        return
    try:
        exc_val = task.exception()
    except asyncio.CancelledError:
        exc_val = asyncio.CancelledError("Task was cancelled")
    if exc_val:
        return type(exc_val), exc_val, exc_val.__traceback__
Пример #11
0
    def __callback_connected(self, task: asyncio.Task) -> None:
        if task.cancelled():
            return

        assert task.done()
        exc = task.exception()
        if exc is not None:
            logger.error("Session %016x: Failed to connect to callback client: %s", self.id, exc)
            self.close()
            return

        assert self.__callback_stub.connected
        self.callback_connected()
Пример #12
0
 def _run_until_task_done(self, task: asyncio.Task, deadline=None):
     try:
         self._wait_timeout = False
         if deadline is not None:
             deadline_handle = self._loop.call_later(max(0, deadline - time.time()), self._set_wait_timeout)
         while not self._wait_timeout and not task.done():
             if len(self._wait_idle_list) == 0:
                 self._run_once()
             else:
                 self._run_until_idle(async_run=True)
     finally:
         if deadline is not None:
             deadline_handle.cancel()
         task.cancel()
Пример #13
0
        def on_timeout(task: asyncio.Task, loop: asyncio.AbstractEventLoop):
            nonlocal cancelled

            if task.done():
                return

            task.cancel()
            cancelled = True

            @asyncio.coroutine
            def waiter():
                yield from task

            loop.create_task(waiter())
Пример #14
0
def get_task_info(task: asyncio.Task) -> Dict:
    def _format_frame(f):
        keys = ["f_code", "f_lineno"]
        return OrderedDict([(k, str(getattr(f, k))) for k in keys])

    info = OrderedDict(
        txt=str(task),
        type=str(type(task)),
        done=task.done(),
        cancelled=False,
        stack=[],
        exception=None,
    )

    if not task.done():
        info["stack"] = [_format_frame(x) for x in task.get_stack()]
    else:
        if task.cancelled():
            info["cancelled"] = True
        else:
            # WARNING: raise if not done or cancelled
            exc = task.exception()
            info["exception"] = f"{type(exc)}: {str(exc)}" if exc else None
    return info
Пример #15
0
async def _cancel_task_if_client_disconnected(
    request: Request, task: asyncio.Task, interval: float = _DEFAULT_CHECK_INTERVAL_S
) -> None:
    try:
        while True:
            if task.done():
                logger.debug("task %s is done", task)
                break
            if await request.is_disconnected():
                logger.warning("client %s disconnected!", request.client)
                task.cancel()
                break
            await asyncio.sleep(interval)
    except CancelledError:
        logger.debug("task was cancelled")
        raise
    finally:
        logger.debug("task completed")
Пример #16
0
    def register_sound(self, group_index: int, sound_index: int,
                       task: asyncio.Task):
        """
        Register that the given task belongs to the given group_index and sound_index. Will automatically
        unregister the task after it has finished.

        Raises a `RuntimeError` if the task is already done. Finished tasks are not allowed to be registered.
        """
        logger.debug(
            f"Registering task for group={group_index}, sound={sound_index}")
        key = self._get_sound_key(group_index, sound_index)
        if task.done():
            raise RuntimeError(
                f"Task for group={group_index}, sound={sound_index} is done, but was registered!"
            )
        task.add_done_callback(
            functools.partial(self._unregister_sound, group_index,
                              sound_index))
        self.sound_to_task[key] = task
Пример #17
0
def wait_task_completed(task: asyncio.Task):
    if task.done() or task.cancelled():
        return
    signal = Event()
    task.add_done_callback(lambda x: signal.set())
    signal.wait()
Пример #18
0
 def _cancel_timer(self, timer: asyncio.Task):
     if timer is not None and not timer.done():
         timer.cancel()