python类sleep()的实例源码

election.py 文件源码 项目:octopus 作者: ideascf 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def _election(self):
        for retry in range(constant.Election.MAX_RETRY):
            try:
                self._locker.acquire(
                    blocking=False,
                    lock_ttl=constant.Election.LOCKER_TTL,
                    timeout=constant.Election.TIMEOUT
                )
            except etcd.EtcdLockExpired as e:
                log.warn(e)
            except Exception as e:
                log.warn(e)
            else:
                # May got locker
                break

            gevent.sleep(constant.Election.LOCK_INTERVAL)
demo_client.py 文件源码 项目:octopus 作者: ideascf 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def main():
    while True:
        service = sel.get_service(5)
        print service

        if service:
            sock = socket.socket()
            try:
                sock.connect(tuple(service.addr.values()))
                sock.send('ping')
                print sock.recv(1024)
            except Exception as e:
                print e
                pass

        gevent.sleep(1)
octp_server.py 文件源码 项目:octopus 作者: ideascf 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def _publish(self):
        """
        Start coroutine for publish.
        :return:
        """

        for retry in range(constant.ETCD_RECONNECT_MAX_RETRY_INIT):
            try:
                co = gevent.spawn(self._publish_handler)
                co.join(constant.ETCD_CONNECT_TIMEOUT)

                e = co.exception
                if e:  # if _publish_handler raise some exception, reraise it.
                    raise e
                else:
                    co.kill()
            except (etcd.EtcdConnectionFailed, gevent.Timeout):
                log.info('Connect to etcd failed, Retry(%d)...', retry)
                gevent.sleep(constant.ETCD_RECONNECT_INTERVAL)
            else:
                log.info('Publish OK.')
                break
        else:  # publish failed
            raise err.OctpEtcdConnectError('Max attempts exceeded.')
runners.py 文件源码 项目:microservices 作者: viatoriche 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def gevent_run(app, monkey_patch=True, start=True, debug=False,
               **kwargs):  # pragma: no cover
    """Run your app in gevent.spawn, run simple loop if start == True

    :param app: queues.Microservice instance
    :param monkey_patch: boolean, use gevent.monkey.patch_all() for patching standard modules, default: True
    :param start: boolean, if True, server will be start (simple loop)
    :param kwargs: other params for WSGIServer(**kwargs)
    :return: server
    """
    if monkey_patch:
        from gevent import monkey

        monkey.patch_all()

    import gevent

    gevent.spawn(app.run, debug=debug, **kwargs)

    if start:
        while not app.stopped:
            gevent.sleep(0.1)
SocketProcess.py 文件源码 项目:jumpscale_portal 作者: jumpscale7 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def _timer(self):
        """
        will remember time every 1/10 sec
        """
        while True:
            # self.epochbin=struct.pack("I",time.time())
            self.epoch = time.time()
            gevent.sleep(0.1)

    # def _taskSchedulerTimer(self):
    #     """
    #     every 4 seconds check maintenance queue
    #     """
    #     while True:
    #         gevent.sleep(5)
    #         self.scheduler.check(self.epoch)
test_tracer.py 文件源码 项目:dd-trace-py 作者: DataDog 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def test_propagation_with_new_context(self):
        # create multiple futures so that we expect multiple
        # traces instead of a single one
        ctx = Context(trace_id=100, span_id=101)
        self.tracer.context_provider.activate(ctx)

        def greenlet():
            with self.tracer.trace('greenlet') as span:
                gevent.sleep(0.01)

        jobs = [gevent.spawn(greenlet) for x in range(1)]
        gevent.joinall(jobs)

        traces = self.tracer.writer.pop_traces()
        eq_(1, len(traces))
        eq_(1, len(traces[0]))
        eq_(traces[0][0].trace_id, 100)
        eq_(traces[0][0].parent_id, 101)
window.py 文件源码 项目:cursed 作者: johannestaas 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def sleep(cls, seconds=0):
        '''
        Tell the CursedWindow's greenlet to sleep for seconds.
        This should be used to allow other CursedWindow's greenlets to execute,
        especially if you have long running code in your ``update`` classmethod.

        This is purely a restriction imposed by gevent, the concurrency library
        used for cursed. It is not truly parallel, so one long running greenlet
        can lock up execution of other windows. Calling cls.sleep() even with
        zero seconds (default) will allow other greenlets to start execution
        again.

        There is no benefit to calling sleep with a number other than zero. Zero
        will allow other greenlets to take over just fine.

        :param seconds: seconds to sleep. default zero is fine.
        '''
        return gevent.sleep(seconds)
app.py 文件源码 项目:cursed 作者: johannestaas 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def _input_loop(self):
        while self.running:
            for cw in self.windows:
                if cw.THREAD.exception is not None:
                    for cw in self.windows:
                        cw.RUNNING = False
                    self.running = False
                    break
                if cw.RUNNING and cw.WAIT:
                    break
            else:
                self.running = False
                break
            gevent.sleep(0)
            c = self.window.getch()
            if c == -1:
                continue
            for cw in self.windows:
                cw.KEY_EVENTS.put(c)
currency_network.py 文件源码 项目:relay 作者: trustlines-network 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def _watch_filter(self, eventname, function, params=None):
        while True:
            try:
                filter = self._proxy.on(eventname, params)
                filter.watch(function)
                logger.info('Connected to filter for {}'.format(eventname))
                return filter
            except socket.timeout as err:
                logger.warning('Timeout in filter creation, try to reconnect: ' + str(err))
                gevent.sleep(reconnect_interval)
            except socket.error as err:
                logger.warning('Socketerror in filter creation, try to reconnect:' + str(err))
                gevent.sleep(reconnect_interval)
            except ValueError as err:
                logger.warning('ValueError in filter creation, try to reconnect:' + str(err))
                gevent.sleep(reconnect_interval)
dota_bot.py 文件源码 项目:Dota2-EU-Ladder 作者: UncleVasya 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def ban_command(bot, command):
        print
        print 'Ban command:'
        print command

        try:
            name = command.split(' ')[1]
        except (IndexError, ValueError):
            return

        bot.send_lobby_message('Banning %s in...' % name)
        for i in range(5, 0, -1):
            gevent.sleep(1)
            bot.send_lobby_message('%d' % i)

        gevent.sleep(1)
        bot.send_lobby_message('JUST A PRANK!')
proxy.py 文件源码 项目:CN_POI_Data 作者: lyBigdata 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def checkAlive(self,ip,port,protocol):
        testUrl = "https://www.baidu.com/"
        req_timeout = 3
        cookies = urllib2.HTTPCookieProcessor()

        proxyHost = ""
        if protocol == 'HTTP' or protocol == 'HTTPS':
            proxyHost = {"http":r'http://%s:%s' % (ip, port)}
            #print proxyHost

        proxyHandler = urllib2.ProxyHandler(proxyHost)
        opener = urllib2.build_opener(cookies, proxyHandler)
        opener.addheaders = [('User-Agent',
                              'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36')]

        try:
            req = opener.open(testUrl, timeout=req_timeout)
            result = req.read()
            #print result
            gevent.sleep(2)
            return  True
        except urllib2.HTTPError as e:
            print  e.message
            return False
test_exception.py 文件源码 项目:takumi 作者: elemepi 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def test_timeout():
    from takumi.service import ServiceHandler, ApiMap, Context
    import gevent
    app = ServiceHandler('TestService', soft_timeout=0, hard_timeout=1)

    class UnknownException(Exception):
        def __init__(self, exc):
            self.exc = exc

    @app.handle_system_exception
    def system_exception(tp, value, tb):
        exc = UnknownException(value)
        return UnknownException, exc, tb

    @app.api
    def timeout():
        gevent.sleep(2)

    api_map = ApiMap(app, Context({'client_addr': 'localhost', 'meta': {}}))
    with pytest.raises(UnknownException) as exc:
        api_map.timeout()
    assert str(exc.value.exc) == 'Timeout after 1 seconds'
dispatcher.py 文件源码 项目:reddit-service-websockets 作者: reddit 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def listen(self, namespace, max_timeout):
        """Register to listen to a namespace and yield messages as they arrive.

        If no messages arrive within `max_timeout` seconds, this will yield a
        `None` to allow clients to do periodic actions like send PINGs.

        This will run forever and yield items as an iterable. Use it in a loop
        and break out of it when you want to deregister.

        """
        queue = gevent.queue.Queue()

        namespace = namespace.rstrip("/")
        for ns in _walk_namespace_hierarchy(namespace):
            self.consumers.setdefault(ns, []).append(queue)

        try:
            while True:
                # jitter the timeout a bit to ensure we don't herd
                timeout = max_timeout - random.uniform(0, max_timeout / 2)

                try:
                    yield queue.get(block=True, timeout=timeout)
                except gevent.queue.Empty:
                    yield None

                # ensure we're not starving others by spinning
                gevent.sleep()
        finally:
            for ns in _walk_namespace_hierarchy(namespace):
                self.consumers[ns].remove(queue)
                if not self.consumers[ns]:
                    del self.consumers[ns]
recipe-577491.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_subscribe():
        e = Observer()
        print '000',getcurrent()
        getcurrent().in_another_greenlet = in_another_greenlet
        b = e.subscribe('kill',getcurrent().in_another_greenlet)
        gevent.sleep(5)
        print 'END'
        b.unsubscribe()
recipe-577491.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_wait():
        e = Observer()
        ev = e.wait('kill')
        try:
            gevent.sleep(3)
        except FiredEvent:
            print 'Fired!'
        else:
            print 'Not Fired!'
        finally:
            ev.cancel()
recipe-577491.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def fire_event():
        e2 = Observer()
        gevent.sleep(2)
        e2.fire('kill')
distribution.py 文件源码 项目:Pyrlang 作者: esl 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def connect(self, node) -> bool:
        """ Looks up EPMD daemon and connects to it trying to discover other 
            Erlang nodes.
        """
        while True:
            if self.epmd_.connect():
                return self.epmd_.alive2(self)

            gevent.sleep(5)
node.py 文件源码 项目:Pyrlang 作者: esl 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def _run(self):
        while not self.is_exiting_:
            self.handle_inbox()
            gevent.sleep(0.0)
node.py 文件源码 项目:Pyrlang 作者: esl 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def dist_command(self, receiver_node: str, message: tuple) -> None:
        """ Locate the connection to the given node (a string).
            Place a tuple crafted by the caller into message box for Erlang
            distribution socket. It will pick up and handle the message whenever
            possible.

            :param receiver_node: Name of a remote node
            :param message: A crafted tuple with command name and some more
                values
        """
        if receiver_node not in self.dist_nodes_:
            LOG("Node: connect to node", receiver_node)
            handler = self.dist_.connect_to_node(
                this_node=self,
                remote_node=receiver_node)

            if handler is None:
                raise NodeException("Node not connected %s" % receiver_node)

            # block until connected, and get the connected message
            LOG("Node: wait for 'node_connected'")
            # msg = self.inbox_.receive_wait(
            #     filter_fn=lambda m: m[0] == 'node_connected'
            # )
            while receiver_node not in self.dist_nodes_:
                gevent.sleep(0.1)

            LOG("Node: connected")

        conn = self.dist_nodes_[receiver_node]
        conn.inbox_.put(message)


问题


面经


文章

微信
公众号

扫码关注公众号