Пример #1
0
    def _register_periodic_task(
        self,
        task_callable: Callable,
        period: float,
        start_at: Optional[datetime.datetime],
    ) -> None:
        """
        Register function to run periodically.

        :param task_callable: function to be called
        :param pediod: float: in seconds
        :param start_at: optional datetime, when to run task for the first time, otherwise call it right now

        :return: None
        """
        if task_callable in self._periodic_tasks:  # pragma: nocover
            # already registered
            return

        periodic_caller = PeriodicCaller(
            partial(self._execution_control, task_callable),
            period=period,
            start_at=start_at,
            exception_callback=self._periodic_task_exception_callback,
            loop=self._loop,
        )
        self._periodic_tasks[task_callable] = periodic_caller
        periodic_caller.start()
        self.logger.debug(f"Periodic task {task_callable} registered.")
Пример #2
0
    def _register_behaviour(self, behaviour: Behaviour) -> None:
        """
        Register behaviour to run periodically.

        :param behaviour: Behaviour object

        :return: None
        """
        if behaviour in self._behaviours_registry:
            # already registered
            return

        periodic_caller = PeriodicCaller(
            partial(
                self._agent._execution_control,  # pylint: disable=protected-access # TODO: refactoring!
                behaviour.act_wrapper,
                behaviour,
            ),
            behaviour.tick_interval,
            behaviour.start_at,
            self._behaviour_exception_callback,
            self._loop,
        )
        self._behaviours_registry[behaviour] = periodic_caller
        periodic_caller.start()
        self.logger.debug(f"Behaviour {behaviour} registered.")
Пример #3
0
async def test_periodic_caller_start_stop():
    """Test start stop calls for PeriodicCaller."""
    called = 0

    def callback():
        nonlocal called
        called += 1

    periodic_caller = PeriodicCaller(callback, period=0.1)
    periodic_caller.start()

    await asyncio.sleep(0.15)
    assert called >= 1

    periodic_caller.stop()
    old_called = called
    await asyncio.sleep(0.15)
    assert old_called == called
Пример #4
0
async def test_periodic_caller_exception():
    """Test exception raises for PeriodicCaller."""
    exception_called = False

    def exception_callback(*args, **kwargs):
        nonlocal exception_called
        exception_called = True

    def callback():
        raise Exception("expected")

    periodic_caller = PeriodicCaller(callback,
                                     period=0.1,
                                     exception_callback=exception_callback)
    periodic_caller.start()

    await asyncio.sleep(0.15)
    assert exception_called
    periodic_caller.stop()