How to use the gevent.spawn function in gevent

To help you get started, we’ve selected a few gevent 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 gevent / gevent / greentest / test__greenlet.py View on Github external
def _test_kill_running(self, block):
        link_test = []
        g = gevent.spawn(gevent.sleep, 10)
        g.link(lambda x: link_test.append(x))
        self._test_kill(g, block=block)
        gevent.sleep(0.01)
        assert link_test == [g]
github gevent / gevent / greentest / test__api.py View on Github external
def test_timer_fired(self):
        lst = [1]

        def func():
            gevent.spawn_later(0.01, lst.pop)
            gevent.sleep(0.02)

        gevent.spawn(func)
        assert lst == [1], lst
        gevent.sleep(0.03)
        assert lst == [], lst
github feisuzhu / thbattle / src / autoupdate.py View on Github external
stats.append(s)
                noti.send()

        remote = self.remote
        remote.transfer_progress = progress

        def do_fetch():
            try:
                return remote.fetch()
            except Exception as e:
                return e

        fetch = hub.threadpool.spawn(do_fetch)

        while True:
            noti_w = gevent.spawn(lambda: hub.wait(noti))
            for r in gevent.iwait([noti_w, fetch]):
                break

            noti_w.kill()

            if r is fetch:
                rst = r.get()
                if isinstance(rst, Exception):
                    raise rst
                else:
                    return

            v = None
            with lock:
                if stats:
                    v = stats[-1]
github mushorg / buttinsky / buttinsky.py View on Github external
self.servers = []
        if not os.path.isfile("conf/buttinsky.cfg"):
            sys.exit("Modify and rename conf/buttinsky.cfg.dist to conf/buttinsky.cfg.")
        hpfeeds_logger.HPFeedsLogger()
        messageQueue = queue.Queue()
        gevent.spawn(MonitorSpawner(messageQueue).work)
        buttinsky_config = ConfigObj("conf/buttinsky.cfg")
        hostname = buttinsky_config["xmlrpc"]["server"]
        port = int(buttinsky_config["xmlrpc"]["port"])
        server = SimpleXMLRPCServer((hostname, port), logRequests=False)
        logger.debug("Listening on port 8000...")
        server.register_instance(ButtinskyXMLRPCServer(messageQueue))
        if buttinsky_config["hpfeeds"]["enabled"] == "True":
            gevent.spawn(ButtinskyXMLRPCServer(messageQueue).load_sink)
        try:
            xmlrpc_server = gevent.spawn(server.serve_forever)
            cli_thread = gevent.spawn(cli.main)
            cli_thread.join()
            xmlrpc_server.kill()
        except (KeyboardInterrupt, SystemExit):
            logger.debug("Quitting... Bye!")
github ADOOO / DnslogSqlinj / dnslogSql.py View on Github external
def threadRun(self, length, model):
		print '[*]Get data count: {}'.format(colored(length,'red'))
		queue = Queue()
		for i in range(length):
			queue.put(i)

		gevent_pool = []

		for i in range(self.thread_count):
			gevent_pool.append(gevent.spawn(self.dumps, queue, model))
		gevent.joinall(gevent_pool)
github fcwu / docker-lightop / web / lightop / __init__.py View on Github external
#            upper = True
        #    headers.append('%s: %s' % (k, request.environ[header]))
        return headers

    #https://stackoverflow.com/questions/18240358/html5-websocket-connecting-to-python
    client = request.environ['wsgi.websocket']
    url = '%s:%d' % (ipaddr, port)
    if len(path) > 0:
        url += '/' + path
    logging.info('websocket: ' + url)
    headers = []
    #headers = get_headers()
    #logging.info('headers: ' + str(headers))
    server = websocket.create_connection("ws://" + url, header=headers)
    try:
        spawn(c2s, client, server)
        while True:
            inp = server.recv()
            if inp is None:
                raise WebSocketError()
            client.send(inp)
    except WebSocketError as e:
        logging.error(e)
    except client.WebSocketConnectionClosedException:
        pass
    return json.dumps({'status': 200})
github ooici / pyon / prototype / speed / sspeed.py View on Github external
time.sleep(2)
        ct = time.time()
        elapsed_s = ct - st

        mps = counter / elapsed_s

        print counter, "messages, per sec:", mps

def work():
    global counter
    while True:
        pub.publish(str(counter))
        counter += 1

_gt = gevent.spawn(tick)
_gw = gevent.spawn(work)

gevent.joinall([_gt, _gw])
github jazzband / django-ddp / dddp / postgres.py View on Github external
key = msg[len(msg_prefix):-1]
                self.logger.warning(
                    'Ignoring unknown settings.DATABASES[%r] option: %s=%r',
                    self.connection.alias,
                    key, conn_params.pop(key),
                )
        self.poll(conn)  # wait for conneciton to start

        import logging
        logging.getLogger('dddp').info('=> Started PostgresGreenlet.')

        cur = conn.cursor()
        cur.execute('LISTEN "ddp";')
        while not self._stop_event.is_set():
            try:
                self.select_greenlet = gevent.spawn(
                    gevent.select.select,
                    [conn], [], [], timeout=None,
                )
                self.select_greenlet.get()
            except gevent.GreenletExit:
                self._stop_event.set()
            finally:
                self.select_greenlet = None
            self.poll(conn)
        self.poll(conn)
        cur.close()
        self.poll(conn)
        conn.close()
github pebble / pypkjs / timeline / blobdb.py View on Github external
def run(self):
        gevent.spawn(self.check_pending_acks)
        gevent.spawn(self.send_queued_data)
github dfm / osrc / fetch.py View on Github external
f = NamedTemporaryFile("wb", delete=False)
        f.write(r.content)
        f.flush()
        os.fsync(f.fileno())
        f.close()
        shutil.move(f.name, local_fn)


if __name__ == "__main__":
    for year, month in product(range(2011, 2014), range(1, 13)):
        jobs = []
        for n, day in product(range(1, 32), range(24)):
            kwargs = {"year": year, "month": month, "day": day, "n": n}
            local_fn = filename.format(**kwargs)
            if not os.path.exists(local_fn):
                jobs.append(gevent.spawn(fetch, **kwargs))
        gevent.joinall(jobs)
        print("Finished {0}-{1}".format(year, month))