Exemplo n.º 1
0
    def emit_after(
        self,
        delay: float,
        name: str,
        args: tuple = (),
        kwargs: dict = None,
        loop: asyncio.AbstractEventLoop = None,
        retries: int = None,
    ):
        """
        Emit an event after a given period of time.

        :param delay: a float of the time (in seconds) you want to delay the call
        :param name: event name
        :param args: additional event arguments
        :param kwargs: addition event keyword arguments
        :param loop: asyncio event loop from which you want the event to be emitted
        """
        # event = self._events.get(name)
        loop = loop or self.loop
        assert loop.is_running()
        loop.call_later(delay,
                        self.emit,
                        name,
                        args=args,
                        kwargs=kwargs,
                        retries=retries,
                        loop=loop)
Exemplo n.º 2
0
async def start_server(loop: asyncio.AbstractEventLoop):
    server = Server()
    await server.init()
    server.set_endpoint("opc.tcp://0.0.0.0:4840/freeopcua/server/")
    # setup our own namespace, not really necessary but should as spec
    uri = "http://examples.freeopcua.github.io"
    idx = await server.register_namespace(uri)
    # get Objects node, this is where we should put our custom stuff
    objects = server.get_objects_node()
    # populating our address space
    myobj = await objects.add_object(idx, "MyObject")
    # Creating a custom event: Approach 1
    # The custom event object automatically will have members from its parent (BaseEventType)
    etype = await server.create_custom_event_type(
        idx, 'MyFirstEvent', ua.ObjectIds.BaseEventType,
        [('MyNumericProperty', ua.VariantType.Float),
         ('MyStringProperty', ua.VariantType.String)])
    myevgen = await server.get_event_generator(etype, myobj)
    # Creating a custom event: Approach 2
    custom_etype = await server.nodes.base_event_type.add_object_type(
        2, 'MySecondEvent')
    await custom_etype.add_property(2, 'MyIntProperty',
                                    ua.Variant(0, ua.VariantType.Int32))
    await custom_etype.add_property(2, 'MyBoolProperty',
                                    ua.Variant(True, ua.VariantType.Boolean))
    mysecondevgen = await server.get_event_generator(custom_etype, myobj)
    await server.start()
    loop.call_later(2, emmit_event, loop, myevgen, mysecondevgen, 1)
Exemplo n.º 3
0
def emmit_event(loop: asyncio.AbstractEventLoop, myevgen: EventGenerator, mysecondevgen: EventGenerator, count: int):
    myevgen.event.Message = ua.LocalizedText("MyFirstEvent %d" % count)
    myevgen.event.Severity = count
    myevgen.event.MyNumericProperty = count
    myevgen.event.MyStringProperty = "Property %d" % count
    myevgen.trigger()
    mysecondevgen.trigger(message="MySecondEvent %d" % count)
    count += 1
    loop.call_later(2, emmit_event, loop, myevgen, mysecondevgen, count)
Exemplo n.º 4
0
async def main(loop: asyncio.AbstractEventLoop):
    # 공유 이벤트 생성
    event = asyncio.Event()
    print(f"event start state: {event.is_set()}")

    loop.call_later(0.1, functools.partial(set_event, event))

    await asyncio.wait([coro1(event), coro2(event)])
    print(f"event end state: {event.is_set()}")
Exemplo n.º 5
0
def autostop_loop(
    temp_event_loop: asyncio.AbstractEventLoop, ) -> asyncio.AbstractEventLoop:
    # Create a new event loop, and arrange for that loop to end almost
    # immediately.  This will allow the calls to main() in these tests to
    # also exit almost immediately.  Otherwise, the foreground test
    # process will hang.
    temp_event_loop.call_later(AUTOSTOP_DELAY, temp_event_loop.stop)
    #
    return temp_event_loop
Exemplo n.º 6
0
def update_current_time(loop: asyncio.AbstractEventLoop) -> None:
    """缓存当前时间,用于管理timeout,缓存于全局变量CURRENT_TIME.

    Parameters:

        loop (asyncio.AbstractEventLoop) : - 服务使用的事件循环

    """
    global CURRENT_TIME
    CURRENT_TIME = time()
    loop.call_later(1, partial(update_current_time, loop))
Exemplo n.º 7
0
def test_asyncio_run_sync_multiple(
    asyncio_event_loop: asyncio.AbstractEventLoop,
) -> None:
    """Regression test for #304."""
    asyncio_event_loop.call_later(0.5, asyncio_event_loop.stop)
    for _ in range(3):
        asyncio_event_loop.run_until_complete(to_thread.run_sync(time.sleep, 0))

    for t in threading.enumerate():
        if t.name == "AnyIO worker thread":
            t.join(2)
            assert not t.is_alive()
Exemplo n.º 8
0
async def main(loop: asyncio.AbstractEventLoop):
    # 공유 락의 생성과 획득
    lock = asyncio.Lock()
    print("acquiring the lock before starting coroutines")
    await lock.acquire()
    print(f"lock acquired: {lock.locked()}")

    # 락을 해제하기 위한 콜백 예약
    loop.call_later(0.1, functools.partial(unlock, lock))

    # 락을 사용하려는 코루틴을 실행
    print("waiting for coroutines")
    await asyncio.wait([coro1(lock), coro2(lock)])
Exemplo n.º 9
0
async def test_select(loop: asyncio.AbstractEventLoop):
    f_one = asyncio.Event()
    f_two = asyncio.Event()

    loop.call_soon(f_one.set)
    loop.call_later(1, f_two.set)

    one, two = await aiomisc.select(f_one.wait(), f_two.wait())

    assert one
    assert two is None

    one, two = await aiomisc.select(f_one.wait(), f_two.wait())
    assert one
Exemplo n.º 10
0
    def run_forever(self, loop: asyncio.AbstractEventLoop = None):
        """
        Creates an event loop and runs the server forever.
        :param asyncio.AbstractEventLoop loop: the event loop to use
        """
        loop = loop or asyncio.get_event_loop()
        self.start_listening(loop)

        def wakeup():
            """Needed for Windows to notice Ctrl-C and other signals"""
            loop.call_later(0.1, wakeup)

        loop.call_later(0.1, wakeup)

        loop.run_forever()
Exemplo n.º 11
0
    def __init__(self, loop: asyncio.AbstractEventLoop,
                 controller: IController, market_events: MarketEvents,
                 frequency_limiter: FrequencyLimiter, speed: float):
        """Initialise a new instance of the ExecutionChannel class."""
        self.competitor: Optional[Competitor] = None
        self.controller: IController = controller
        self.closing: bool = False
        self.data: bytes = b""
        self.event_loop: asyncio.AbstractEventLoop = loop
        self.file_number: int = -1
        self.frequency_limiter: FrequencyLimiter = frequency_limiter
        self.logger: logging.Logger = logging.getLogger("EXECUTION")
        self.login_timeout: asyncio.Handle = loop.call_later(1.0, self.close)
        self.market_events: MarketEvents = market_events
        self.name: Optional[str] = None
        self.transport: Optional[asyncio.Transport] = None
        self.speed: float = speed
        self.start_time: float = 0.0

        self.account_message: bytearray = bytearray(
            POSITION_CHANGE_MESSAGE_SIZE)
        self.error_message: bytearray = bytearray(ERROR_MESSAGE_SIZE)
        self.order_message: bytearray = bytearray(ORDER_STATUS_MESSAGE_SIZE)

        HEADER.pack_into(self.error_message, 0, ERROR_MESSAGE_SIZE,
                         MessageType.ERROR)
        HEADER.pack_into(self.account_message, 0, POSITION_CHANGE_MESSAGE_SIZE,
                         MessageType.POSITION_CHANGE)
        HEADER.pack_into(self.order_message, 0, ORDER_STATUS_MESSAGE_SIZE,
                         MessageType.ORDER_STATUS)
Exemplo n.º 12
0
 def __init__(self, dt: datetime.datetime, *,
              loop: asyncio.AbstractEventLoop) -> None:
     self.loop: asyncio.AbstractEventLoop = loop
     self.future: asyncio.Future[None] = loop.create_future()
     relative_delta = discord.utils.compute_timedelta(dt)
     self.handle = loop.call_later(relative_delta, self.future.set_result,
                                   True)
Exemplo n.º 13
0
    def _handle(self, loop: asyncio.AbstractEventLoop, delay: float,
                event: Event, event_simulator: EventSimulator):
        delayed_handler = DelayedHandler()
        self.handlers.add(delayed_handler)

        loop = loop or asyncio.get_event_loop()
        timer_handler = loop.call_later(delay, delayed_handler)

        delayed_handler.event = event
        delayed_handler.event_simulator = event_simulator
        delayed_handler.timer_handler = timer_handler
        delayed_handler.handlers = self.handlers
Exemplo n.º 14
0
    async def _wait(self, fs, return_when=FIRST_COMPLETED, *, add:bool=False, loop:AbstractEventLoop=None, 
                            timeout:int=None):
        """A modified version of _wait in asyncio.

        The fs argument must be a collection of Futures.
        """
        if(not len(fs)): return [], self.pending

        timeout_handle = None
        if(loop is None):
            loop = self.loop

        if timeout is not None:
            timeout_handle = loop.call_later(timeout, _release_waiter, self.waiter)
        
        if(add):
            self.counter += len(fs)
        else:
            self.counter = len(fs)

        def __on_completion(f):
            self.counter -= 1
            if (self.counter <= 0 or
                return_when == FIRST_COMPLETED or
                return_when == FIRST_EXCEPTION and (not f.cancelled() and
                                                    f.exception() is not None)):
                if timeout_handle is not None:
                    timeout_handle.cancel()
                if not self.waiter.done():
                    self.waiter.set_result(None)

        for f in fs:
            f.add_done_callback(__on_completion)

        try:
            await self.waiter
        finally:
            if timeout_handle is not None:
                timeout_handle.cancel()
            for f in fs:
                f.remove_done_callback(__on_completion)

        if(not add):
            done, pending = set(), set()
            for f in fs:
                if f.done():
                    done.add(f)
                else:
                    pending.add(f)
                
            return done, pending
Exemplo n.º 15
0
def future_with_timeout(loop: asyncio.AbstractEventLoop,
                        timeout: Union[int, float],
                        future: asyncio.Future=None) -> asyncio.Future:

    loop = loop or asyncio.get_event_loop()
    f = future or create_future(loop=loop)

    def on_timeout():
        if f.done():
            return
        f.set_exception(asyncio.TimeoutError)

    if timeout:
        handler = loop.call_later(timeout, on_timeout)

        def on_result(*_):
            with suppress(Exception):
                handler.cancel()

        f.add_done_callback(on_result)

    return f
Exemplo n.º 16
0
def run_reboot_loop(loop: asyncio.AbstractEventLoop):
    """
    Run the bot, and re-run it if it fails or disconnects. The bot will still stop if an error
    bubbles outside the event loop, in the case that KeyboardInterrupt is raised (Ctrl+C/SIGINT),
    or that sys.exit() is called.
    """
    def reset_backoff(backoff: Backoff, sequence):
        if sequence == backoff.n:  # don't do it if we had a retry in the meantime
            backoff.reset()

    logger.info("Welcome to KazTron v{}, booting up...".format(kaztron.__version__))

    # noinspection PyBroadException
    try:
        bo_timer = Backoff(initial_time=3.0, base=1.58, max_attempts=12)
        wait_time = 0
        while True:
            reset_task = loop.call_later(wait_time, reset_backoff, bo_timer, bo_timer.n)
            run(loop)
            logger.error("Bot halted unexpectedly.")
            reset_task.cancel()
            wait_time = bo_timer.next()
            logger.info("Restarting bot in {:.1f} seconds...".format(wait_time))
            time.sleep(wait_time)
            logger.info("Restarting bot...")
    except StopIteration:
        logger.error("Too many failed attempts. Exiting.")
        sys.exit(ErrorCodes.RETRY_MAX_ATTEMPTS)
    except KeyboardInterrupt:  # outside of runner.run
        logger.info("Interrupted by user. Exiting.")
    except Exception:
        logger.exception("Exception in reboot loop.")
        raise
    finally:
        logger.info("Exiting.")
        loop.close()
Exemplo n.º 17
0
    def __init__(self, loop: asyncio.AbstractEventLoop,
                 competitor_manager: CompetitorManager,
                 frequency_limiter: FrequencyLimiter, timer: Timer):
        """Initialise a new instance of the ExecutionChannel class."""
        Connection.__init__(self)

        self.competitor: Optional[Competitor] = None
        self.competitor_manager: CompetitorManager = competitor_manager
        self.closing: bool = False
        self.frequency_limiter: FrequencyLimiter = frequency_limiter
        self.logger: logging.Logger = logging.getLogger("EXECUTION")
        self.login_timeout: asyncio.Handle = loop.call_later(1.0, self.close)
        self.timer: Timer = timer

        self.__error_message = bytearray(ERROR_MESSAGE_SIZE)
        self.__order_status_message = bytearray(ORDER_STATUS_MESSAGE_SIZE)
        self.__order_filled_message = bytearray(ORDER_FILLED_MESSAGE_SIZE)

        HEADER.pack_into(self.__error_message, 0, ERROR_MESSAGE_SIZE,
                         MessageType.ERROR)
        HEADER.pack_into(self.__order_status_message, 0,
                         ORDER_STATUS_MESSAGE_SIZE, MessageType.ORDER_STATUS)
        HEADER.pack_into(self.__order_filled_message, 0,
                         ORDER_FILLED_MESSAGE_SIZE, MessageType.ORDER_FILLED)
Exemplo n.º 18
0
def trampoline(loop: AbstractEventLoop, name: str = "") -> None:
    print(name, end=" ")
    print_now()
    loop.call_later(random.random(), trampoline, loop, name)
    loop.call_later(random.random(), trampoline, loop, name)
Exemplo n.º 19
0
 def update_screen(self, end_time, loop: asyncio.AbstractEventLoop, screen: Screen):
     screen.draw_next_frame()
     if loop.time() < end_time:
         loop.call_later(0.05, self.update_screen, end_time, loop, screen)
     else:
         loop.stop()
Exemplo n.º 20
0
 def _wakeup(loop: asyncio.AbstractEventLoop,
             delay: float = 1.0) -> None:
     loop.call_later(delay, _wakeup, loop, delay)