How to use the curio.timeout_after function in curio

To help you get started, we’ve selected a few curio examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github povilasb / udptest / udptest / client.py View on Github external
async def _run_test(self) -> None:
        recv_task = await curio.spawn(self._recv_packets)
        await self._send_packets()
        print('All packets sent')
        try:
            await curio.timeout_after(self._timeout, recv_task.join())
        except curio.TaskTimeout:
            await recv_task.cancel()
github guyingbo / shadowproxy / tests / test_udp.py View on Github external
async def make_request(bind_addr):
    async with curio.timeout_after(60):
        r = await subprocess.run(
            ["dig", "+short", f"@{bind_addr[0]}", "-p", f"{bind_addr[1]}", "baidu.com"]
        )
        assert r.returncode == 0
github guyingbo / shadowproxy / tests / test_http_request.py View on Github external
async def make_request(client, url=None):
    if url is None:
        url = url_http
    headers = ["User-Agent: curl/7.54.0", "Accept: */*"]
    async with client:
        async with curio.timeout_after(40):
            response = await client.http_request(url, headers=headers)
            assert response.size > 0
github dabeaz / curio / tests / test_channel.py View on Github external
async def client(c):
        try:
            msg = 'x' * 10000000
            await timeout_after(1, c.send(msg))
            await timeout_after(1, c.send(msg))
            results.append('success')
        except TaskTimeout:
            results.append('timeout')
github dabeaz / curio / examples / hello.py View on Github external
kid_task = await curio.spawn(kid)
    await curio.sleep(5)

    print('Yes, go play')
    await start_evt.set()
    await goodbye.wait()
    del goodbye

    print("Let's go")
    count_task = await curio.spawn(countdown, 10)
    await count_task.join()

    print("We're leaving!")
    try:
        await curio.timeout_after(10, kid_task.join)
    except curio.TaskTimeout:
        print('I warned you!')
        await kid_task.cancel()
    print('Leaving!')
github Fuyukai / curious / curious / voice_old / voice_gateway.py View on Github external
def _heartbeat_loop(gw: 'VoiceGateway', heartbeat_interval: float):
    """
    Heartbeat looper that loops and sends heartbeats to the gateway.

    :param gw: The gateway to handle.
    """
    # async threads!
    logger.debug("Sending initial heartbeat.")
    AWAIT(gw.send_heartbeat())
    while True:
        # this is similar to the normal threaded event waiter
        # it will time out after heartbeat_interval seconds.
        try:
            AWAIT(curio.timeout_after(heartbeat_interval, gw._stop_heartbeating.wait()))
        except curio.TaskTimeout:
            pass
        else:
            break

        try:
            AWAIT(gw.send_heartbeat())
        except ReconnectWebsocket:
            break
github allenling / magne / magne / process_worker / worker_pool.py View on Github external
async def watch_worker(self, wobj):
        func_name, args = wobj.func, wobj.args
        self.logger.debug('watching worker %s for %s(%s)' % (wobj.ident, func_name, args))
        success, res = False, None
        canceled = False
        try:
            # timeout will cancel coro
            success, res = await curio.timeout_after(self.worker_timeout, wobj.recv)
        except curio.TaskTimeout:
            # got timeout
            self.logger.error('worker %s run %s(%s) timeout!' % (wobj.ident, func_name, args))
            self.kill_worker(wobj)
            self.logger.info('shutdown worker %s...' % wobj.ident)
            if self.alive is True:
                # do not create new worker process while closing worker pool
                self.manage_worker()
        except curio.CancelledError:
            self.logger.info('watch %s cancel' % wobj.ident)
            canceled = True
        else:
            self.logger.info('worker %s run %s(%s) return %s, %s' % (wobj.ident, func_name, args, success, res))
            del self.busy_workers[wobj.ident]
            self.idle_workers.append(wobj.ident)
        del self.watch_tasks[wobj.ident]
github allenling / magne / magne / helper.py View on Github external
try:
            # 302: An operator intervened to close the connection for some reason. The client may retry at some later date.
            # close channel first
            close_channel_frame = pika.spec.Channel.Close(reply_code=302, reply_text='close connection',
                                                          class_id=0, method_id=0)
            close_channel_frame_value = pika.frame.Method(self.channel_number, close_channel_frame)
            await self.sock.sendall(close_channel_frame_value.marshal())
            await curio.timeout_after(1, self.assert_recv_method, pika.spec.Channel.CloseOk)
            self.channel_number = 0
            self.logger.info('closed channel')

            close_connection_frame = pika.spec.Connection.Close(reply_code=302, reply_text='close connection',
                                                                class_id=0, method_id=0)
            frame_value = pika.frame.Method(self.channel_number, close_connection_frame)
            await self.sock.sendall(frame_value.marshal())
            await curio.timeout_after(1, self.assert_recv_method, pika.spec.Connection.CloseOk)
            self.logger.info('closed connection')
        except curio.TaskTimeout:
            self.logger.error('send close connection frame got CloseOk TaskTimeout')
        except ConnectionResetError:
            self.logger.error('send close connection frame ConnectionResetError')
        except Exception as e:
            self.logger.error('send close connection frame exception: %s' % e, exc_info=True)
        self.logger.info('closed amqp connection')
        return
github omarryhan / aiogoogle / aiogoogle / sessions / curio_asks_session.py View on Github external
async def execute_tasks():
            async with curio.TaskGroup() as g:
                if full_res is True:
                    tasks = [
                        await g.spawn(get_response, request) for request in requests
                    ]
                else:
                    tasks = [
                        await g.spawn(get_content, request) for request in requests
                    ]
            return await curio.gather(tasks)

        session_factory = self.__class__ if session_factory is None else session_factory

        if timeout is not None:
            async with curio.timeout_after(timeout):
                results = await execute_tasks()
        else:
            results = await execute_tasks()

        if isinstance(results, list) and len(results) == 1:
            return results[0]
        else:
            return results
github python-hyper / h11 / examples / curio-server.py View on Github external
async def http_serve(sock, addr):
    wrapper = CurioHTTPWrapper(sock)
    while True:
        assert wrapper.conn.states == {
            h11.CLIENT: h11.IDLE, h11.SERVER: h11.IDLE}

        try:
            async with curio.timeout_after(TIMEOUT):
                wrapper.info("Server main loop waiting for request")
                event = await wrapper.next_event()
                wrapper.info("Server main loop got event:", event)
                if type(event) is h11.Request:
                    await send_echo_response(wrapper, event)
        except Exception as exc:
            wrapper.info("Error during response handler:", exc)
            await maybe_send_error_response(wrapper, exc)

        if wrapper.conn.our_state is h11.MUST_CLOSE:
            wrapper.info("connection is not reusable, so shutting down")
            await wrapper.shutdown_and_clean_up()
            return
        else:
            try:
                wrapper.info("trying to re-use connection")