我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用tornado.ioloop.start()。
def stop(self): """Stop the I/O loop. If the event loop is not currently running, the next call to `start()` will return immediately. To use asynchronous methods from otherwise-synchronous code (such as unit tests), you can start and stop the event loop like this:: ioloop = IOLoop() async_method(ioloop=ioloop, callback=ioloop.stop) ioloop.start() ``ioloop.start()`` will return after ``async_method`` has run its callback, whether that callback was invoked before or after ``ioloop.start``. Note that even after `stop` has been called, the `IOLoop` is not completely stopped until `IOLoop.start` has also returned. Some work that was scheduled before the call to `stop` may still be run before the `IOLoop` shuts down. """ raise NotImplementedError()
def main(): tornado.options.parse_command_line() print "ws_rpc main is running, exit with ctrl+c" logging.info("creating application") app = create_app() logging.info("creating server") server = create_server(app) logging.info("starting ioloop thread") thread = threading.Thread(target=start_ioloop) thread.start() try: while(True): time.sleep(1) except KeyboardInterrupt: server.stop() stop_ioloop() thread.join()
def main(): ''' main ?? ''' # ?? search_engin_server ioloop = tornado.ioloop.IOLoop.instance() server = tornado.httpserver.HTTPServer(Application(), xheaders=True) server.listen(options.port) def sig_handler(sig, _): ''' ?????? ''' logging.warn("Caught signal: %s", sig) shutdown(ioloop, server) signal.signal(signal.SIGTERM, sig_handler) signal.signal(signal.SIGINT, sig_handler) ioloop.start()
def add_callback_from_signal(self, callback, *args, **kwargs): with stack_context.NullContext(): if thread.get_ident() != self._thread_ident: # if the signal is handled on another thread, we can add # it normally (modulo the NullContext) self.add_callback(callback, *args, **kwargs) else: # If we're on the IOLoop's thread, we cannot use # the regular add_callback because it may deadlock on # _callback_lock. Blindly insert into self._callbacks. # This is safe because the GIL makes list.append atomic. # One subtlety is that if the signal interrupted the # _callback_lock block in IOLoop.start, we may modify # either the old or new version of self._callbacks, # but either way will work. self._callbacks.append(functools.partial( stack_context.wrap(callback), *args, **kwargs))
def start_consuming(self): """Exchange, channel, consumer ready to start listening""" # send rpc request self.worker_id = None self.correlation_id = uuid.uuid4().hex self._channel.basic_publish( exchange=self.exchange, routing_key='%s.worker.%s' % (self.key, self.worker_type), properties=pika.BasicProperties( reply_to=self.queue, correlation_id=self.correlation_id, content_type='application/json', ), body=json.dumps(self.worker_kwargs), ) log.info("%s: sent RPC request, will wait for response.", self.lbl) super(_HubTornadoConsumer, self).start_consuming()
def main(): parse_command_line() redis.connect(host=options.redis_host) app = tornado.web.Application( [ (r'/', MainHandler), (r'/oauth', OAuthHandler), (r'/command', CommandHandler), (r'/button', ButtonHandler), ], template_path=os.path.join(os.path.dirname(__file__), 'templates'), static_path=os.path.join(os.path.dirname(__file__), 'static'), debug=options.debug, ) app.listen(options.port) ioloop = tornado.ioloop.IOLoop.current() ioloop.start()
def post(self): global login_timer disconnect = self.get_argument('disconnect', default='False') if disconnect != 'False': client_manager.free() self.redirect('/', permanent=True) return interval = self.get_argument('login_interval', default='1') try: interval = int(interval) except: interval = 1 login_timer.stop() login_timer = tornado.ioloop.PeriodicCallback(client_manager.do_login, interval * 1000, ioloop) #3 secondes login_timer.start() self.redirect('/', permanent=True)
def close(self, all_fds=False): """Closes the `IOLoop`, freeing any resources used. If ``all_fds`` is true, all file descriptors registered on the IOLoop will be closed (not just the ones created by the `IOLoop` itself). Many applications will only use a single `IOLoop` that runs for the entire lifetime of the process. In that case closing the `IOLoop` is not necessary since everything will be cleaned up when the process exits. `IOLoop.close` is provided mainly for scenarios such as unit tests, which create and destroy a large number of ``IOLoops``. An `IOLoop` must be completely stopped before it can be closed. This means that `IOLoop.stop()` must be called *and* `IOLoop.start()` must be allowed to return before attempting to call `IOLoop.close()`. Therefore the call to `close` will usually appear just after the call to `start` rather than near the call to `stop`. .. versionchanged:: 3.1 If the `IOLoop` implementation supports non-integer objects for "file descriptors", those objects will have their ``close`` method when ``all_fds`` is true. """ raise NotImplementedError()
def start(self): """Starts the I/O loop. The loop will run until one of the callbacks calls `stop()`, which will make the loop stop after the current event iteration completes. """ raise NotImplementedError()
def _setup_logging(self): """The IOLoop catches and logs exceptions, so it's important that log output be visible. However, python's default behavior for non-root loggers (prior to python 3.2) is to print an unhelpful "no handlers could be found" message rather than the actual log entry, so we must explicitly configure logging if we've made it this far without anything. This method should be called from start() in subclasses. """ if not any([logging.getLogger().handlers, logging.getLogger('tornado').handlers, logging.getLogger('tornado.application').handlers]): logging.basicConfig()
def start(self): """Starts the timer.""" self._running = True self._next_timeout = self.io_loop.time() self._schedule_next()
def add_callback(self, callback, *args, **kwargs): if thread.get_ident() != self._thread_ident: # If we're not on the IOLoop's thread, we need to synchronize # with other threads, or waking logic will induce a race. with self._callback_lock: if self._closing: return list_empty = not self._callbacks self._callbacks.append(functools.partial( stack_context.wrap(callback), *args, **kwargs)) if list_empty: # If we're not in the IOLoop's thread, and we added the # first callback to an empty list, we may need to wake it # up (it may wake up on its own, but an occasional extra # wake is harmless). Waking up a polling IOLoop is # relatively expensive, so we try to avoid it when we can. self._waker.wake() else: if self._closing: return # If we're on the IOLoop's thread, we don't need the lock, # since we don't need to wake anyone, just add the # callback. Blindly insert into self._callbacks. This is # safe even from signal handlers because the GIL makes # list.append atomic. One subtlety is that if the signal # is interrupting another thread holding the # _callback_lock block in IOLoop.start, we may modify # either the old or new version of self._callbacks, but # either way will work. self._callbacks.append(functools.partial( stack_context.wrap(callback), *args, **kwargs))
def main(): ioloop = tornado.ioloop.IOLoop.instance() http_server = tornado.httpserver.HTTPServer(Windseed()) http_server.listen(8000, 'localhost') ioloop.start()
def __init__(self, port=None, uri=None, debug=False): """Create http server, register callbacks and start immediatelly.""" #nprint(uri, debug=debug) re_uri = re.compile('/' + uri ) txt_uri = re_uri.pattern re_uri_sr = re.compile('/pathman_sr' ) txt_uri_sr = re_uri_sr.pattern build_odl_topology(debug=debug) logging.info('patterned to ' + repr(txt_uri)) ##tuple_register2 = (txt_uri, CommandHandler2, dict(debug=debug)) tuple_register_sr = (txt_uri_sr, CommandHandlerSR, dict(debug=debug)) application = tornado.web.Application([ tuple_register_sr, # For Pathman_sr backend #tuple_register2, # For regular Pathman backend (r'/cisco-ctao/apps/(.*)', tornado.web.StaticFileHandler, {"path": "client"}), # For UI #(r'/pathman/topology', dataHandler), # For BGP APP ], dict(debug=debug)) """ http_server = tornado.httpserver.HTTPServer(application, ssl_options={ "certfile": os.path.join(data_dir, "server.crt"), "keyfile": os.path.join(data_dir, "server.key"), }) """ #http_server.listen(int(port)) application.listen(int(port)) ioloop = tornado.ioloop.IOLoop.instance() #nprint('Pathman REST API Launched on port %s' % port, debug=debug) logging.info('Pathman REST API Launched on port %s' % port) ioloop.start()
def start_ioloop(): logging.info("ws_rpc ioloop started") ioloop = tornado.ioloop.IOLoop.instance() ioloop.start() logging.info("ws_rpc ioloop stopped")
def _actually_run(self, postbind_cb): import logging import tornado.options logging.getLogger().setLevel(logging.INFO) tornado.options.enable_pretty_logging() import tornado.web import tornado.httpserver import tornado.ioloop import tornado.autoreload import hashlib import random m = hashlib.md5() m.update(str(random.random()) + str(random.random())) secret = m.digest() app = tornado.web.Application(self.handlers, static_path=self.static, cookie_secret=secret) http_server = tornado.httpserver.HTTPServer(app) http_server.listen(self.port) logging.info("waiting for requests on http://%s:%d" % (self.hostname or "localhost", self.port)) ioloop = tornado.ioloop.IOLoop.instance() tornado.autoreload.start(ioloop) postbind_cb() ioloop.start()