{
    "file_diffs": [
        {
            "old_file_content": "#\n# Copyright 2009 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"An I/O event loop for non-blocking sockets.\n\nOn Python 3, `.IOLoop` is a wrapper around the `asyncio` event loop.\n\nTypical applications will use a single `IOLoop` object, accessed via\n`IOLoop.current` class method. The `IOLoop.start` method (or\nequivalently, `asyncio.AbstractEventLoop.run_forever`) should usually\nbe called at the end of the ``main()`` function. Atypical applications\nmay use more than one `IOLoop`, such as one `IOLoop` per thread, or\nper `unittest` case.\n\nIn addition to I/O events, the `IOLoop` can also schedule time-based\nevents. `IOLoop.add_timeout` is a non-blocking alternative to\n`time.sleep`.\n\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nimport collections\nimport datetime\nimport errno\nimport functools\nimport heapq\nimport itertools\nimport logging\nimport numbers\nimport os\nimport select\nimport sys\nimport threading\nimport time\nimport traceback\nimport math\n\nfrom tornado.concurrent import Future, is_future, chain_future, future_set_exc_info, future_add_done_callback  # noqa: E501\nfrom tornado.log import app_log, gen_log\nfrom tornado.platform.auto import set_close_exec, Waker\nfrom tornado import stack_context\nfrom tornado.util import (\n    PY3, Configurable, errno_from_exception, timedelta_to_seconds,\n    TimeoutError, unicode_type, import_object,\n)\n\ntry:\n    import signal\nexcept ImportError:\n    signal = None\n\ntry:\n    from concurrent.futures import ThreadPoolExecutor\nexcept ImportError:\n    ThreadPoolExecutor = None\n\nif PY3:\n    import _thread as thread\nelse:\n    import thread\n\ntry:\n    import asyncio\nexcept ImportError:\n    asyncio = None\n\n\n_POLL_TIMEOUT = 3600.0\n\n\nclass IOLoop(Configurable):\n    \"\"\"A level-triggered I/O loop.\n\n    On Python 3, `IOLoop` is a wrapper around the `asyncio` event\n    loop. On Python 2, it uses ``epoll`` (Linux) or ``kqueue`` (BSD\n    and Mac OS X) if they are available, or else we fall back on\n    select(). If you are implementing a system that needs to handle\n    thousands of simultaneous connections, you should use a system\n    that supports either ``epoll`` or ``kqueue``.\n\n    Example usage for a simple TCP server:\n\n    .. testcode::\n\n        import errno\n        import functools\n        import socket\n\n        import tornado.ioloop\n        from tornado import gen\n        from tornado.iostream import IOStream\n\n        @gen.coroutine\n        def handle_connection(connection, address):\n            stream = IOStream(connection)\n            message = yield stream.read_until_close()\n            print(\"message from client:\", message.decode().strip())\n\n        def connection_ready(sock, fd, events):\n            while True:\n                try:\n                    connection, address = sock.accept()\n                except socket.error as e:\n                    if e.args[0] not in (errno.EWOULDBLOCK, errno.EAGAIN):\n                        raise\n                    return\n                connection.setblocking(0)\n                handle_connection(connection, address)\n\n        if __name__ == '__main__':\n            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)\n            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n            sock.setblocking(0)\n            sock.bind((\"\", 8888))\n            sock.listen(128)\n\n            io_loop = tornado.ioloop.IOLoop.current()\n            callback = functools.partial(connection_ready, sock)\n            io_loop.add_handler(sock.fileno(), callback, io_loop.READ)\n            io_loop.start()\n\n    .. testoutput::\n       :hide:\n\n    By default, a newly-constructed `IOLoop` becomes the thread's current\n    `IOLoop`, unless there already is a current `IOLoop`. This behavior\n    can be controlled with the ``make_current`` argument to the `IOLoop`\n    constructor: if ``make_current=True``, the new `IOLoop` will always\n    try to become current and it raises an error if there is already a\n    current instance. If ``make_current=False``, the new `IOLoop` will\n    not try to become current.\n\n    In general, an `IOLoop` cannot survive a fork or be shared across\n    processes in any way. When multiple processes are being used, each\n    process should create its own `IOLoop`, which also implies that\n    any objects which depend on the `IOLoop` (such as\n    `.AsyncHTTPClient`) must also be created in the child processes.\n    As a guideline, anything that starts processes (including the\n    `tornado.process` and `multiprocessing` modules) should do so as\n    early as possible, ideally the first thing the application does\n    after loading its configuration in ``main()``.\n\n    .. versionchanged:: 4.2\n       Added the ``make_current`` keyword argument to the `IOLoop`\n       constructor.\n\n    .. versionchanged:: 5.0\n\n       Uses the `asyncio` event loop by default. The\n       ``IOLoop.configure`` method cannot be used on Python 3 except\n       to redundantly specify the `asyncio` event loop.\n\n    \"\"\"\n    # Constants from the epoll module\n    _EPOLLIN = 0x001\n    _EPOLLPRI = 0x002\n    _EPOLLOUT = 0x004\n    _EPOLLERR = 0x008\n    _EPOLLHUP = 0x010\n    _EPOLLRDHUP = 0x2000\n    _EPOLLONESHOT = (1 << 30)\n    _EPOLLET = (1 << 31)\n\n    # Our events map exactly to the epoll events\n    NONE = 0\n    READ = _EPOLLIN\n    WRITE = _EPOLLOUT\n    ERROR = _EPOLLERR | _EPOLLHUP\n\n    # In Python 2, _current.instance points to the current IOLoop.\n    _current = threading.local()\n\n    # In Python 3, _ioloop_for_asyncio maps from asyncio loops to IOLoops.\n    _ioloop_for_asyncio = dict()\n\n    @classmethod\n    def configure(cls, impl, **kwargs):\n        if asyncio is not None:\n            from tornado.platform.asyncio import BaseAsyncIOLoop\n\n            if isinstance(impl, (str, unicode_type)):\n                impl = import_object(impl)\n            if not issubclass(impl, BaseAsyncIOLoop):\n                raise RuntimeError(\n                    \"only AsyncIOLoop is allowed when asyncio is available\")\n        super(IOLoop, cls).configure(impl, **kwargs)\n\n    @staticmethod\n    def instance():\n        \"\"\"Deprecated alias for `IOLoop.current()`.\n\n        .. versionchanged:: 5.0\n\n           Previously, this method returned a global singleton\n           `IOLoop`, in contrast with the per-thread `IOLoop` returned\n           by `current()`. In nearly all cases the two were the same\n           (when they differed, it was generally used from non-Tornado\n           threads to communicate back to the main thread's `IOLoop`).\n           This distinction is not present in `asyncio`, so in order\n           to facilitate integration with that package `instance()`\n           was changed to be an alias to `current()`. Applications\n           using the cross-thread communications aspect of\n           `instance()` should instead set their own global variable\n           to point to the `IOLoop` they want to use.\n\n        .. deprecated:: 5.0\n        \"\"\"\n        return IOLoop.current()\n\n    def install(self):\n        \"\"\"Deprecated alias for `make_current()`.\n\n        .. versionchanged:: 5.0\n\n           Previously, this method would set this `IOLoop` as the\n           global singleton used by `IOLoop.instance()`. Now that\n           `instance()` is an alias for `current()`, `install()`\n           is an alias for `make_current()`.\n\n        .. deprecated:: 5.0\n        \"\"\"\n        self.make_current()\n\n    @staticmethod\n    def clear_instance():\n        \"\"\"Deprecated alias for `clear_current()`.\n\n        .. versionchanged:: 5.0\n\n           Previously, this method would clear the `IOLoop` used as\n           the global singleton by `IOLoop.instance()`. Now that\n           `instance()` is an alias for `current()`,\n           `clear_instance()` is an alias for `clear_current()`.\n\n        .. deprecated:: 5.0\n\n        \"\"\"\n        IOLoop.clear_current()\n\n    @staticmethod\n    def current(instance=True):\n        \"\"\"Returns the current thread's `IOLoop`.\n\n        If an `IOLoop` is currently running or has been marked as\n        current by `make_current`, returns that instance.  If there is\n        no current `IOLoop` and ``instance`` is true, creates one.\n\n        .. versionchanged:: 4.1\n           Added ``instance`` argument to control the fallback to\n           `IOLoop.instance()`.\n        .. versionchanged:: 5.0\n           On Python 3, control of the current `IOLoop` is delegated\n           to `asyncio`, with this and other methods as pass-through accessors.\n           The ``instance`` argument now controls whether an `IOLoop`\n           is created automatically when there is none, instead of\n           whether we fall back to `IOLoop.instance()` (which is now\n           an alias for this method). ``instance=False`` is deprecated,\n           since even if we do not create an `IOLoop`, this method\n           may initialize the asyncio loop.\n        \"\"\"\n        if asyncio is None:\n            current = getattr(IOLoop._current, \"instance\", None)\n            if current is None and instance:\n                current = IOLoop()\n                if IOLoop._current.instance is not current:\n                    raise RuntimeError(\"new IOLoop did not become current\")\n        else:\n            try:\n                loop = asyncio.get_event_loop()\n            except (RuntimeError, AssertionError):\n                if not instance:\n                    return None\n                raise\n            try:\n                return IOLoop._ioloop_for_asyncio[loop]\n            except KeyError:\n                if instance:\n                    from tornado.platform.asyncio import AsyncIOMainLoop\n                    current = AsyncIOMainLoop(make_current=True)\n                else:\n                    current = None\n        return current\n\n    def make_current(self):\n        \"\"\"Makes this the `IOLoop` for the current thread.\n\n        An `IOLoop` automatically becomes current for its thread\n        when it is started, but it is sometimes useful to call\n        `make_current` explicitly before starting the `IOLoop`,\n        so that code run at startup time can find the right\n        instance.\n\n        .. versionchanged:: 4.1\n           An `IOLoop` created while there is no current `IOLoop`\n           will automatically become current.\n\n        .. versionchanged:: 5.0\n           This method also sets the current `asyncio` event loop.\n        \"\"\"\n        # The asyncio event loops override this method.\n        assert asyncio is None\n        old = getattr(IOLoop._current, \"instance\", None)\n        if old is not None:\n            old.clear_current()\n        IOLoop._current.instance = self\n\n    @staticmethod\n    def clear_current():\n        \"\"\"Clears the `IOLoop` for the current thread.\n\n        Intended primarily for use by test frameworks in between tests.\n\n        .. versionchanged:: 5.0\n           This method also clears the current `asyncio` event loop.\n        \"\"\"\n        old = IOLoop.current(instance=False)\n        if old is not None:\n            old._clear_current_hook()\n        if asyncio is None:\n            IOLoop._current.instance = None\n\n    def _clear_current_hook(self):\n        \"\"\"Instance method called when an IOLoop ceases to be current.\n\n        May be overridden by subclasses as a counterpart to make_current.\n        \"\"\"\n        pass\n\n    @classmethod\n    def configurable_base(cls):\n        return IOLoop\n\n    @classmethod\n    def configurable_default(cls):\n        if asyncio is not None:\n            from tornado.platform.asyncio import AsyncIOLoop\n            return AsyncIOLoop\n        return PollIOLoop\n\n    def initialize(self, make_current=None):\n        if make_current is None:\n            if IOLoop.current(instance=False) is None:\n                self.make_current()\n        elif make_current:\n            current = IOLoop.current(instance=False)\n            # AsyncIO loops can already be current by this point.\n            if current is not None and current is not self:\n                raise RuntimeError(\"current IOLoop already exists\")\n            self.make_current()\n\n    def close(self, all_fds=False):\n        \"\"\"Closes the `IOLoop`, freeing any resources used.\n\n        If ``all_fds`` is true, all file descriptors registered on the\n        IOLoop will be closed (not just the ones created by the\n        `IOLoop` itself).\n\n        Many applications will only use a single `IOLoop` that runs for the\n        entire lifetime of the process.  In that case closing the `IOLoop`\n        is not necessary since everything will be cleaned up when the\n        process exits.  `IOLoop.close` is provided mainly for scenarios\n        such as unit tests, which create and destroy a large number of\n        ``IOLoops``.\n\n        An `IOLoop` must be completely stopped before it can be closed.  This\n        means that `IOLoop.stop()` must be called *and* `IOLoop.start()` must\n        be allowed to return before attempting to call `IOLoop.close()`.\n        Therefore the call to `close` will usually appear just after\n        the call to `start` rather than near the call to `stop`.\n\n        .. versionchanged:: 3.1\n           If the `IOLoop` implementation supports non-integer objects\n           for \"file descriptors\", those objects will have their\n           ``close`` method when ``all_fds`` is true.\n        \"\"\"\n        raise NotImplementedError()\n\n    def add_handler(self, fd, handler, events):\n        \"\"\"Registers the given handler to receive the given events for ``fd``.\n\n        The ``fd`` argument may either be an integer file descriptor or\n        a file-like object with a ``fileno()`` method (and optionally a\n        ``close()`` method, which may be called when the `IOLoop` is shut\n        down).\n\n        The ``events`` argument is a bitwise or of the constants\n        ``IOLoop.READ``, ``IOLoop.WRITE``, and ``IOLoop.ERROR``.\n\n        When an event occurs, ``handler(fd, events)`` will be run.\n\n        .. versionchanged:: 4.0\n           Added the ability to pass file-like objects in addition to\n           raw file descriptors.\n        \"\"\"\n        raise NotImplementedError()\n\n    def update_handler(self, fd, events):\n        \"\"\"Changes the events we listen for ``fd``.\n\n        .. versionchanged:: 4.0\n           Added the ability to pass file-like objects in addition to\n           raw file descriptors.\n        \"\"\"\n        raise NotImplementedError()\n\n    def remove_handler(self, fd):\n        \"\"\"Stop listening for events on ``fd``.\n\n        .. versionchanged:: 4.0\n           Added the ability to pass file-like objects in addition to\n           raw file descriptors.\n        \"\"\"\n        raise NotImplementedError()\n\n    def set_blocking_signal_threshold(self, seconds, action):\n        \"\"\"Sends a signal if the `IOLoop` is blocked for more than\n        ``s`` seconds.\n\n        Pass ``seconds=None`` to disable.  Requires Python 2.6 on a unixy\n        platform.\n\n        The action parameter is a Python signal handler.  Read the\n        documentation for the `signal` module for more information.\n        If ``action`` is None, the process will be killed if it is\n        blocked for too long.\n\n        .. deprecated:: 5.0\n\n           Not implemented on the `asyncio` event loop. Use the environment\n           variable ``PYTHONASYNCIODEBUG=1`` instead.\n        \"\"\"\n        raise NotImplementedError()\n\n    def set_blocking_log_threshold(self, seconds):\n        \"\"\"Logs a stack trace if the `IOLoop` is blocked for more than\n        ``s`` seconds.\n\n        Equivalent to ``set_blocking_signal_threshold(seconds,\n        self.log_stack)``\n\n        .. deprecated:: 5.0\n\n           Not implemented on the `asyncio` event loop. Use the environment\n           variable ``PYTHONASYNCIODEBUG=1`` instead.\n        \"\"\"\n        self.set_blocking_signal_threshold(seconds, self.log_stack)\n\n    def log_stack(self, signal, frame):\n        \"\"\"Signal handler to log the stack trace of the current thread.\n\n        For use with `set_blocking_signal_threshold`.\n        \"\"\"\n        gen_log.warning('IOLoop blocked for %f seconds in\\n%s',\n                        self._blocking_signal_threshold,\n                        ''.join(traceback.format_stack(frame)))\n\n    def start(self):\n        \"\"\"Starts the I/O loop.\n\n        The loop will run until one of the callbacks calls `stop()`, which\n        will make the loop stop after the current event iteration completes.\n        \"\"\"\n        raise NotImplementedError()\n\n    def _setup_logging(self):\n        \"\"\"The IOLoop catches and logs exceptions, so it's\n        important that log output be visible.  However, python's\n        default behavior for non-root loggers (prior to python\n        3.2) is to print an unhelpful \"no handlers could be\n        found\" message rather than the actual log entry, so we\n        must explicitly configure logging if we've made it this\n        far without anything.\n\n        This method should be called from start() in subclasses.\n        \"\"\"\n        if not any([logging.getLogger().handlers,\n                    logging.getLogger('tornado').handlers,\n                    logging.getLogger('tornado.application').handlers]):\n            logging.basicConfig()\n\n    def stop(self):\n        \"\"\"Stop the I/O loop.\n\n        If the event loop is not currently running, the next call to `start()`\n        will return immediately.\n\n        To use asynchronous methods from otherwise-synchronous code (such as\n        unit tests), you can start and stop the event loop like this::\n\n          ioloop = IOLoop()\n          async_method(ioloop=ioloop, callback=ioloop.stop)\n          ioloop.start()\n\n        ``ioloop.start()`` will return after ``async_method`` has run\n        its callback, whether that callback was invoked before or\n        after ``ioloop.start``.\n\n        Note that even after `stop` has been called, the `IOLoop` is not\n        completely stopped until `IOLoop.start` has also returned.\n        Some work that was scheduled before the call to `stop` may still\n        be run before the `IOLoop` shuts down.\n        \"\"\"\n        raise NotImplementedError()\n\n    def run_sync(self, func, timeout=None):\n        \"\"\"Starts the `IOLoop`, runs the given function, and stops the loop.\n\n        The function must return either a yieldable object or\n        ``None``. If the function returns a yieldable object, the\n        `IOLoop` will run until the yieldable is resolved (and\n        `run_sync()` will return the yieldable's result). If it raises\n        an exception, the `IOLoop` will stop and the exception will be\n        re-raised to the caller.\n\n        The keyword-only argument ``timeout`` may be used to set\n        a maximum duration for the function.  If the timeout expires,\n        a `tornado.util.TimeoutError` is raised.\n\n        This method is useful in conjunction with `tornado.gen.coroutine`\n        to allow asynchronous calls in a ``main()`` function::\n\n            @gen.coroutine\n            def main():\n                # do stuff...\n\n            if __name__ == '__main__':\n                IOLoop.current().run_sync(main)\n\n        .. versionchanged:: 4.3\n           Returning a non-``None``, non-yieldable value is now an error.\n\n        .. versionchanged:: 5.0\n           If a timeout occurs, the ``func`` coroutine will be cancelled.\n        \"\"\"\n        future_cell = [None]\n\n        def run():\n            try:\n                result = func()\n                if result is not None:\n                    from tornado.gen import convert_yielded\n                    result = convert_yielded(result)\n            except Exception:\n                future_cell[0] = Future()\n                future_set_exc_info(future_cell[0], sys.exc_info())\n            else:\n                if is_future(result):\n                    future_cell[0] = result\n                else:\n                    future_cell[0] = Future()\n                    future_cell[0].set_result(result)\n            self.add_future(future_cell[0], lambda future: self.stop())\n        self.add_callback(run)\n        if timeout is not None:\n            def timeout_callback():\n                # If we can cancel the future, do so and wait on it. If not,\n                # Just stop the loop and return with the task still pending.\n                # (If we neither cancel nor wait for the task, a warning\n                # will be logged).\n                if not future_cell[0].cancel():\n                    self.stop()\n            timeout_handle = self.add_timeout(self.time() + timeout, timeout_callback)\n        self.start()\n        if timeout is not None:\n            self.remove_timeout(timeout_handle)\n        if future_cell[0].cancelled() or not future_cell[0].done():\n            raise TimeoutError('Operation timed out after %s seconds' % timeout)\n        return future_cell[0].result()\n\n    def time(self):\n        \"\"\"Returns the current time according to the `IOLoop`'s clock.\n\n        The return value is a floating-point number relative to an\n        unspecified time in the past.\n\n        By default, the `IOLoop`'s time function is `time.time`.  However,\n        it may be configured to use e.g. `time.monotonic` instead.\n        Calls to `add_timeout` that pass a number instead of a\n        `datetime.timedelta` should use this function to compute the\n        appropriate time, so they can work no matter what time function\n        is chosen.\n        \"\"\"\n        return time.time()\n\n    def add_timeout(self, deadline, callback, *args, **kwargs):\n        \"\"\"Runs the ``callback`` at the time ``deadline`` from the I/O loop.\n\n        Returns an opaque handle that may be passed to\n        `remove_timeout` to cancel.\n\n        ``deadline`` may be a number denoting a time (on the same\n        scale as `IOLoop.time`, normally `time.time`), or a\n        `datetime.timedelta` object for a deadline relative to the\n        current time.  Since Tornado 4.0, `call_later` is a more\n        convenient alternative for the relative case since it does not\n        require a timedelta object.\n\n        Note that it is not safe to call `add_timeout` from other threads.\n        Instead, you must use `add_callback` to transfer control to the\n        `IOLoop`'s thread, and then call `add_timeout` from there.\n\n        Subclasses of IOLoop must implement either `add_timeout` or\n        `call_at`; the default implementations of each will call\n        the other.  `call_at` is usually easier to implement, but\n        subclasses that wish to maintain compatibility with Tornado\n        versions prior to 4.0 must use `add_timeout` instead.\n\n        .. versionchanged:: 4.0\n           Now passes through ``*args`` and ``**kwargs`` to the callback.\n        \"\"\"\n        if isinstance(deadline, numbers.Real):\n            return self.call_at(deadline, callback, *args, **kwargs)\n        elif isinstance(deadline, datetime.timedelta):\n            return self.call_at(self.time() + timedelta_to_seconds(deadline),\n                                callback, *args, **kwargs)\n        else:\n            raise TypeError(\"Unsupported deadline %r\" % deadline)\n\n    def call_later(self, delay, callback, *args, **kwargs):\n        \"\"\"Runs the ``callback`` after ``delay`` seconds have passed.\n\n        Returns an opaque handle that may be passed to `remove_timeout`\n        to cancel.  Note that unlike the `asyncio` method of the same\n        name, the returned object does not have a ``cancel()`` method.\n\n        See `add_timeout` for comments on thread-safety and subclassing.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        return self.call_at(self.time() + delay, callback, *args, **kwargs)\n\n    def call_at(self, when, callback, *args, **kwargs):\n        \"\"\"Runs the ``callback`` at the absolute time designated by ``when``.\n\n        ``when`` must be a number using the same reference point as\n        `IOLoop.time`.\n\n        Returns an opaque handle that may be passed to `remove_timeout`\n        to cancel.  Note that unlike the `asyncio` method of the same\n        name, the returned object does not have a ``cancel()`` method.\n\n        See `add_timeout` for comments on thread-safety and subclassing.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        return self.add_timeout(when, callback, *args, **kwargs)\n\n    def remove_timeout(self, timeout):\n        \"\"\"Cancels a pending timeout.\n\n        The argument is a handle as returned by `add_timeout`.  It is\n        safe to call `remove_timeout` even if the callback has already\n        been run.\n        \"\"\"\n        raise NotImplementedError()\n\n    def add_callback(self, callback, *args, **kwargs):\n        \"\"\"Calls the given callback on the next I/O loop iteration.\n\n        It is safe to call this method from any thread at any time,\n        except from a signal handler.  Note that this is the **only**\n        method in `IOLoop` that makes this thread-safety guarantee; all\n        other interaction with the `IOLoop` must be done from that\n        `IOLoop`'s thread.  `add_callback()` may be used to transfer\n        control from other threads to the `IOLoop`'s thread.\n\n        To add a callback from a signal handler, see\n        `add_callback_from_signal`.\n        \"\"\"\n        raise NotImplementedError()\n\n    def add_callback_from_signal(self, callback, *args, **kwargs):\n        \"\"\"Calls the given callback on the next I/O loop iteration.\n\n        Safe for use from a Python signal handler; should not be used\n        otherwise.\n\n        Callbacks added with this method will be run without any\n        `.stack_context`, to avoid picking up the context of the function\n        that was interrupted by the signal.\n        \"\"\"\n        raise NotImplementedError()\n\n    def spawn_callback(self, callback, *args, **kwargs):\n        \"\"\"Calls the given callback on the next IOLoop iteration.\n\n        Unlike all other callback-related methods on IOLoop,\n        ``spawn_callback`` does not associate the callback with its caller's\n        ``stack_context``, so it is suitable for fire-and-forget callbacks\n        that should not interfere with the caller.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        with stack_context.NullContext():\n            self.add_callback(callback, *args, **kwargs)\n\n    def add_future(self, future, callback):\n        \"\"\"Schedules a callback on the ``IOLoop`` when the given\n        `.Future` is finished.\n\n        The callback is invoked with one argument, the\n        `.Future`.\n        \"\"\"\n        assert is_future(future)\n        callback = stack_context.wrap(callback)\n        future_add_done_callback(\n            future, lambda future: self.add_callback(callback, future))\n\n    def run_in_executor(self, executor, func, *args):\n        \"\"\"Runs a function in a ``concurrent.futures.Executor``. If\n        ``executor`` is ``None``, the IO loop's default executor will be used.\n\n        Use `functools.partial` to pass keyword arguments to ``func``.\n\n        .. versionadded:: 5.0\n        \"\"\"\n        if ThreadPoolExecutor is None:\n            raise RuntimeError(\n                \"concurrent.futures is required to use IOLoop.run_in_executor\")\n\n        if executor is None:\n            if not hasattr(self, '_executor'):\n                from tornado.process import cpu_count\n                self._executor = ThreadPoolExecutor(max_workers=(cpu_count() * 5))\n            executor = self._executor\n        c_future = executor.submit(func, *args)\n        # Concurrent Futures are not usable with await. Wrap this in a\n        # Tornado Future instead, using self.add_future for thread-safety.\n        t_future = Future()\n        self.add_future(c_future, lambda f: chain_future(f, t_future))\n        return t_future\n\n    def set_default_executor(self, executor):\n        \"\"\"Sets the default executor to use with :meth:`run_in_executor`.\n\n        .. versionadded:: 5.0\n        \"\"\"\n        self._executor = executor\n\n    def _run_callback(self, callback):\n        \"\"\"Runs a callback with error handling.\n\n        For use in subclasses.\n        \"\"\"\n        try:\n            ret = callback()\n            if ret is not None:\n                from tornado import gen\n                # Functions that return Futures typically swallow all\n                # exceptions and store them in the Future.  If a Future\n                # makes it out to the IOLoop, ensure its exception (if any)\n                # gets logged too.\n                try:\n                    ret = gen.convert_yielded(ret)\n                except gen.BadYieldError:\n                    # It's not unusual for add_callback to be used with\n                    # methods returning a non-None and non-yieldable\n                    # result, which should just be ignored.\n                    pass\n                else:\n                    self.add_future(ret, self._discard_future_result)\n        except Exception:\n            self.handle_callback_exception(callback)\n\n    def _discard_future_result(self, future):\n        \"\"\"Avoid unhandled-exception warnings from spawned coroutines.\"\"\"\n        future.result()\n\n    def handle_callback_exception(self, callback):\n        \"\"\"This method is called whenever a callback run by the `IOLoop`\n        throws an exception.\n\n        By default simply logs the exception as an error.  Subclasses\n        may override this method to customize reporting of exceptions.\n\n        The exception itself is not passed explicitly, but is available\n        in `sys.exc_info`.\n        \"\"\"\n        app_log.error(\"Exception in callback %r\", callback, exc_info=True)\n\n    def split_fd(self, fd):\n        \"\"\"Returns an (fd, obj) pair from an ``fd`` parameter.\n\n        We accept both raw file descriptors and file-like objects as\n        input to `add_handler` and related methods.  When a file-like\n        object is passed, we must retain the object itself so we can\n        close it correctly when the `IOLoop` shuts down, but the\n        poller interfaces favor file descriptors (they will accept\n        file-like objects and call ``fileno()`` for you, but they\n        always return the descriptor itself).\n\n        This method is provided for use by `IOLoop` subclasses and should\n        not generally be used by application code.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        try:\n            return fd.fileno(), fd\n        except AttributeError:\n            return fd, fd\n\n    def close_fd(self, fd):\n        \"\"\"Utility method to close an ``fd``.\n\n        If ``fd`` is a file-like object, we close it directly; otherwise\n        we use `os.close`.\n\n        This method is provided for use by `IOLoop` subclasses (in\n        implementations of ``IOLoop.close(all_fds=True)`` and should\n        not generally be used by application code.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        try:\n            try:\n                fd.close()\n            except AttributeError:\n                os.close(fd)\n        except OSError:\n            pass\n\n\nclass PollIOLoop(IOLoop):\n    \"\"\"Base class for IOLoops built around a select-like function.\n\n    For concrete implementations, see `tornado.platform.epoll.EPollIOLoop`\n    (Linux), `tornado.platform.kqueue.KQueueIOLoop` (BSD and Mac), or\n    `tornado.platform.select.SelectIOLoop` (all platforms).\n    \"\"\"\n    def initialize(self, impl, time_func=None, **kwargs):\n        super(PollIOLoop, self).initialize(**kwargs)\n        self._impl = impl\n        if hasattr(self._impl, 'fileno'):\n            set_close_exec(self._impl.fileno())\n        self.time_func = time_func or time.time\n        self._handlers = {}\n        self._events = {}\n        self._callbacks = collections.deque()\n        self._timeouts = []\n        self._cancellations = 0\n        self._running = False\n        self._stopped = False\n        self._closing = False\n        self._thread_ident = None\n        self._pid = os.getpid()\n        self._blocking_signal_threshold = None\n        self._timeout_counter = itertools.count()\n\n        # Create a pipe that we send bogus data to when we want to wake\n        # the I/O loop when it is idle\n        self._waker = Waker()\n        self.add_handler(self._waker.fileno(),\n                         lambda fd, events: self._waker.consume(),\n                         self.READ)\n\n    @classmethod\n    def configurable_base(cls):\n        return PollIOLoop\n\n    @classmethod\n    def configurable_default(cls):\n        if hasattr(select, \"epoll\"):\n            from tornado.platform.epoll import EPollIOLoop\n            return EPollIOLoop\n        if hasattr(select, \"kqueue\"):\n            # Python 2.6+ on BSD or Mac\n            from tornado.platform.kqueue import KQueueIOLoop\n            return KQueueIOLoop\n        from tornado.platform.select import SelectIOLoop\n        return SelectIOLoop\n\n    def close(self, all_fds=False):\n        self._closing = True\n        self.remove_handler(self._waker.fileno())\n        if all_fds:\n            for fd, handler in list(self._handlers.values()):\n                self.close_fd(fd)\n        self._waker.close()\n        self._impl.close()\n        self._callbacks = None\n        self._timeouts = None\n        if hasattr(self, '_executor'):\n            self._executor.shutdown()\n\n    def add_handler(self, fd, handler, events):\n        fd, obj = self.split_fd(fd)\n        self._handlers[fd] = (obj, stack_context.wrap(handler))\n        self._impl.register(fd, events | self.ERROR)\n\n    def update_handler(self, fd, events):\n        fd, obj = self.split_fd(fd)\n        self._impl.modify(fd, events | self.ERROR)\n\n    def remove_handler(self, fd):\n        fd, obj = self.split_fd(fd)\n        self._handlers.pop(fd, None)\n        self._events.pop(fd, None)\n        try:\n            self._impl.unregister(fd)\n        except Exception:\n            gen_log.debug(\"Error deleting fd from IOLoop\", exc_info=True)\n\n    def set_blocking_signal_threshold(self, seconds, action):\n        if not hasattr(signal, \"setitimer\"):\n            gen_log.error(\"set_blocking_signal_threshold requires a signal module \"\n                          \"with the setitimer method\")\n            return\n        self._blocking_signal_threshold = seconds\n        if seconds is not None:\n            signal.signal(signal.SIGALRM,\n                          action if action is not None else signal.SIG_DFL)\n\n    def start(self):\n        if self._running:\n            raise RuntimeError(\"IOLoop is already running\")\n        if os.getpid() != self._pid:\n            raise RuntimeError(\"Cannot share PollIOLoops across processes\")\n        self._setup_logging()\n        if self._stopped:\n            self._stopped = False\n            return\n        old_current = IOLoop.current(instance=False)\n        if old_current is not self:\n            self.make_current()\n        self._thread_ident = thread.get_ident()\n        self._running = True\n\n        # signal.set_wakeup_fd closes a race condition in event loops:\n        # a signal may arrive at the beginning of select/poll/etc\n        # before it goes into its interruptible sleep, so the signal\n        # will be consumed without waking the select.  The solution is\n        # for the (C, synchronous) signal handler to write to a pipe,\n        # which will then be seen by select.\n        #\n        # In python's signal handling semantics, this only matters on the\n        # main thread (fortunately, set_wakeup_fd only works on the main\n        # thread and will raise a ValueError otherwise).\n        #\n        # If someone has already set a wakeup fd, we don't want to\n        # disturb it.  This is an issue for twisted, which does its\n        # SIGCHLD processing in response to its own wakeup fd being\n        # written to.  As long as the wakeup fd is registered on the IOLoop,\n        # the loop will still wake up and everything should work.\n        old_wakeup_fd = None\n        if hasattr(signal, 'set_wakeup_fd') and os.name == 'posix':\n            # requires python 2.6+, unix.  set_wakeup_fd exists but crashes\n            # the python process on windows.\n            try:\n                old_wakeup_fd = signal.set_wakeup_fd(self._waker.write_fileno())\n                if old_wakeup_fd != -1:\n                    # Already set, restore previous value.  This is a little racy,\n                    # but there's no clean get_wakeup_fd and in real use the\n                    # IOLoop is just started once at the beginning.\n                    signal.set_wakeup_fd(old_wakeup_fd)\n                    old_wakeup_fd = None\n            except ValueError:\n                # Non-main thread, or the previous value of wakeup_fd\n                # is no longer valid.\n                old_wakeup_fd = None\n\n        try:\n            while True:\n                # Prevent IO event starvation by delaying new callbacks\n                # to the next iteration of the event loop.\n                ncallbacks = len(self._callbacks)\n\n                # Add any timeouts that have come due to the callback list.\n                # Do not run anything until we have determined which ones\n                # are ready, so timeouts that call add_timeout cannot\n                # schedule anything in this iteration.\n                due_timeouts = []\n                if self._timeouts:\n                    now = self.time()\n                    while self._timeouts:\n                        if self._timeouts[0].callback is None:\n                            # The timeout was cancelled.  Note that the\n                            # cancellation check is repeated below for timeouts\n                            # that are cancelled by another timeout or callback.\n                            heapq.heappop(self._timeouts)\n                            self._cancellations -= 1\n                        elif self._timeouts[0].deadline <= now:\n                            due_timeouts.append(heapq.heappop(self._timeouts))\n                        else:\n                            break\n                    if (self._cancellations > 512 and\n                            self._cancellations > (len(self._timeouts) >> 1)):\n                        # Clean up the timeout queue when it gets large and it's\n                        # more than half cancellations.\n                        self._cancellations = 0\n                        self._timeouts = [x for x in self._timeouts\n                                          if x.callback is not None]\n                        heapq.heapify(self._timeouts)\n\n                for i in range(ncallbacks):\n                    self._run_callback(self._callbacks.popleft())\n                for timeout in due_timeouts:\n                    if timeout.callback is not None:\n                        self._run_callback(timeout.callback)\n                # Closures may be holding on to a lot of memory, so allow\n                # them to be freed before we go into our poll wait.\n                due_timeouts = timeout = None\n\n                if self._callbacks:\n                    # If any callbacks or timeouts called add_callback,\n                    # we don't want to wait in poll() before we run them.\n                    poll_timeout = 0.0\n                elif self._timeouts:\n                    # If there are any timeouts, schedule the first one.\n                    # Use self.time() instead of 'now' to account for time\n                    # spent running callbacks.\n                    poll_timeout = self._timeouts[0].deadline - self.time()\n                    poll_timeout = max(0, min(poll_timeout, _POLL_TIMEOUT))\n                else:\n                    # No timeouts and no callbacks, so use the default.\n                    poll_timeout = _POLL_TIMEOUT\n\n                if not self._running:\n                    break\n\n                if self._blocking_signal_threshold is not None:\n                    # clear alarm so it doesn't fire while poll is waiting for\n                    # events.\n                    signal.setitimer(signal.ITIMER_REAL, 0, 0)\n\n                try:\n                    event_pairs = self._impl.poll(poll_timeout)\n                except Exception as e:\n                    # Depending on python version and IOLoop implementation,\n                    # different exception types may be thrown and there are\n                    # two ways EINTR might be signaled:\n                    # * e.errno == errno.EINTR\n                    # * e.args is like (errno.EINTR, 'Interrupted system call')\n                    if errno_from_exception(e) == errno.EINTR:\n                        continue\n                    else:\n                        raise\n\n                if self._blocking_signal_threshold is not None:\n                    signal.setitimer(signal.ITIMER_REAL,\n                                     self._blocking_signal_threshold, 0)\n\n                # Pop one fd at a time from the set of pending fds and run\n                # its handler. Since that handler may perform actions on\n                # other file descriptors, there may be reentrant calls to\n                # this IOLoop that modify self._events\n                self._events.update(event_pairs)\n                while self._events:\n                    fd, events = self._events.popitem()\n                    try:\n                        fd_obj, handler_func = self._handlers[fd]\n                        handler_func(fd_obj, events)\n                    except (OSError, IOError) as e:\n                        if errno_from_exception(e) == errno.EPIPE:\n                            # Happens when the client closes the connection\n                            pass\n                        else:\n                            self.handle_callback_exception(self._handlers.get(fd))\n                    except Exception:\n                        self.handle_callback_exception(self._handlers.get(fd))\n                fd_obj = handler_func = None\n\n        finally:\n            # reset the stopped flag so another start/stop pair can be issued\n            self._stopped = False\n            if self._blocking_signal_threshold is not None:\n                signal.setitimer(signal.ITIMER_REAL, 0, 0)\n            if old_current is None:\n                IOLoop.clear_current()\n            elif old_current is not self:\n                old_current.make_current()\n            if old_wakeup_fd is not None:\n                signal.set_wakeup_fd(old_wakeup_fd)\n\n    def stop(self):\n        self._running = False\n        self._stopped = True\n        self._waker.wake()\n\n    def time(self):\n        return self.time_func()\n\n    def call_at(self, deadline, callback, *args, **kwargs):\n        timeout = _Timeout(\n            deadline,\n            functools.partial(stack_context.wrap(callback), *args, **kwargs),\n            self)\n        heapq.heappush(self._timeouts, timeout)\n        return timeout\n\n    def remove_timeout(self, timeout):\n        # Removing from a heap is complicated, so just leave the defunct\n        # timeout object in the queue (see discussion in\n        # http://docs.python.org/library/heapq.html).\n        # If this turns out to be a problem, we could add a garbage\n        # collection pass whenever there are too many dead timeouts.\n        timeout.callback = None\n        self._cancellations += 1\n\n    def add_callback(self, callback, *args, **kwargs):\n        if self._closing:\n            return\n        # Blindly insert into self._callbacks. This is safe even\n        # from signal handlers because deque.append is atomic.\n        self._callbacks.append(functools.partial(\n            stack_context.wrap(callback), *args, **kwargs))\n        if thread.get_ident() != self._thread_ident:\n            # This will write one byte but Waker.consume() reads many\n            # at once, so it's ok to write even when not strictly\n            # necessary.\n            self._waker.wake()\n        else:\n            # If we're on the IOLoop's thread, we don't need to wake anyone.\n            pass\n\n    def add_callback_from_signal(self, callback, *args, **kwargs):\n        with stack_context.NullContext():\n            self.add_callback(callback, *args, **kwargs)\n\n\nclass _Timeout(object):\n    \"\"\"An IOLoop timeout, a UNIX timestamp and a callback\"\"\"\n\n    # Reduce memory overhead when there are lots of pending callbacks\n    __slots__ = ['deadline', 'callback', 'tdeadline']\n\n    def __init__(self, deadline, callback, io_loop):\n        if not isinstance(deadline, numbers.Real):\n            raise TypeError(\"Unsupported deadline %r\" % deadline)\n        self.deadline = deadline\n        self.callback = callback\n        self.tdeadline = (deadline, next(io_loop._timeout_counter))\n\n    # Comparison methods to sort by deadline, with object id as a tiebreaker\n    # to guarantee a consistent ordering.  The heapq module uses __le__\n    # in python2.5, and __lt__ in 2.6+ (sort() and most other comparisons\n    # use __lt__).\n    def __lt__(self, other):\n        return self.tdeadline < other.tdeadline\n\n    def __le__(self, other):\n        return self.tdeadline <= other.tdeadline\n\n\nclass PeriodicCallback(object):\n    \"\"\"Schedules the given callback to be called periodically.\n\n    The callback is called every ``callback_time`` milliseconds.\n    Note that the timeout is given in milliseconds, while most other\n    time-related functions in Tornado use seconds.\n\n    If the callback runs for longer than ``callback_time`` milliseconds,\n    subsequent invocations will be skipped to get back on schedule.\n\n    `start` must be called after the `PeriodicCallback` is created.\n\n    .. versionchanged:: 5.0\n       The ``io_loop`` argument (deprecated since version 4.1) has been removed.\n    \"\"\"\n    def __init__(self, callback, callback_time):\n        self.callback = callback\n        if callback_time <= 0:\n            raise ValueError(\"Periodic callback must have a positive callback_time\")\n        self.callback_time = callback_time\n        self._running = False\n        self._timeout = None\n\n    def start(self):\n        \"\"\"Starts the timer.\"\"\"\n        # Looking up the IOLoop here allows to first instantiate the\n        # PeriodicCallback in another thread, then start it using\n        # IOLoop.add_callback().\n        self.io_loop = IOLoop.current()\n        self._running = True\n        self._next_timeout = self.io_loop.time()\n        self._schedule_next()\n\n    def stop(self):\n        \"\"\"Stops the timer.\"\"\"\n        self._running = False\n        if self._timeout is not None:\n            self.io_loop.remove_timeout(self._timeout)\n            self._timeout = None\n\n    def is_running(self):\n        \"\"\"Return True if this `.PeriodicCallback` has been started.\n\n        .. versionadded:: 4.1\n        \"\"\"\n        return self._running\n\n    def _run(self):\n        if not self._running:\n            return\n        try:\n            return self.callback()\n        except Exception:\n            self.io_loop.handle_callback_exception(self.callback)\n        finally:\n            self._schedule_next()\n\n    def _schedule_next(self):\n        if self._running:\n            current_time = self.io_loop.time()\n\n            if self._next_timeout <= current_time:\n                callback_time_sec = self.callback_time / 1000.0\n                self._next_timeout += (math.floor((current_time - self._next_timeout) /\n                                                  callback_time_sec) + 1) * callback_time_sec\n\n            self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run)\n",
            "new_file_content": "#\n# Copyright 2009 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"An I/O event loop for non-blocking sockets.\n\nOn Python 3, `.IOLoop` is a wrapper around the `asyncio` event loop.\n\nTypical applications will use a single `IOLoop` object, accessed via\n`IOLoop.current` class method. The `IOLoop.start` method (or\nequivalently, `asyncio.AbstractEventLoop.run_forever`) should usually\nbe called at the end of the ``main()`` function. Atypical applications\nmay use more than one `IOLoop`, such as one `IOLoop` per thread, or\nper `unittest` case.\n\nIn addition to I/O events, the `IOLoop` can also schedule time-based\nevents. `IOLoop.add_timeout` is a non-blocking alternative to\n`time.sleep`.\n\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nimport collections\nimport datetime\nimport errno\nimport functools\nimport heapq\nimport itertools\nimport logging\nimport numbers\nimport os\nimport select\nimport sys\nimport threading\nimport time\nimport traceback\nimport math\n\nfrom tornado.concurrent import Future, is_future, chain_future, future_set_exc_info, future_add_done_callback  # noqa: E501\nfrom tornado.log import app_log, gen_log\nfrom tornado.platform.auto import set_close_exec, Waker\nfrom tornado import stack_context\nfrom tornado.util import (\n    PY3, Configurable, errno_from_exception, timedelta_to_seconds,\n    TimeoutError, unicode_type, import_object,\n)\n\ntry:\n    import signal\nexcept ImportError:\n    signal = None\n\ntry:\n    from concurrent.futures import ThreadPoolExecutor\nexcept ImportError:\n    ThreadPoolExecutor = None\n\nif PY3:\n    import _thread as thread\nelse:\n    import thread\n\ntry:\n    import asyncio\nexcept ImportError:\n    asyncio = None\n\n\n_POLL_TIMEOUT = 3600.0\n\n\nclass IOLoop(Configurable):\n    \"\"\"A level-triggered I/O loop.\n\n    On Python 3, `IOLoop` is a wrapper around the `asyncio` event\n    loop. On Python 2, it uses ``epoll`` (Linux) or ``kqueue`` (BSD\n    and Mac OS X) if they are available, or else we fall back on\n    select(). If you are implementing a system that needs to handle\n    thousands of simultaneous connections, you should use a system\n    that supports either ``epoll`` or ``kqueue``.\n\n    Example usage for a simple TCP server:\n\n    .. testcode::\n\n        import errno\n        import functools\n        import socket\n\n        import tornado.ioloop\n        from tornado import gen\n        from tornado.iostream import IOStream\n\n        @gen.coroutine\n        def handle_connection(connection, address):\n            stream = IOStream(connection)\n            message = yield stream.read_until_close()\n            print(\"message from client:\", message.decode().strip())\n\n        def connection_ready(sock, fd, events):\n            while True:\n                try:\n                    connection, address = sock.accept()\n                except socket.error as e:\n                    if e.args[0] not in (errno.EWOULDBLOCK, errno.EAGAIN):\n                        raise\n                    return\n                connection.setblocking(0)\n                handle_connection(connection, address)\n\n        if __name__ == '__main__':\n            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)\n            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n            sock.setblocking(0)\n            sock.bind((\"\", 8888))\n            sock.listen(128)\n\n            io_loop = tornado.ioloop.IOLoop.current()\n            callback = functools.partial(connection_ready, sock)\n            io_loop.add_handler(sock.fileno(), callback, io_loop.READ)\n            io_loop.start()\n\n    .. testoutput::\n       :hide:\n\n    By default, a newly-constructed `IOLoop` becomes the thread's current\n    `IOLoop`, unless there already is a current `IOLoop`. This behavior\n    can be controlled with the ``make_current`` argument to the `IOLoop`\n    constructor: if ``make_current=True``, the new `IOLoop` will always\n    try to become current and it raises an error if there is already a\n    current instance. If ``make_current=False``, the new `IOLoop` will\n    not try to become current.\n\n    In general, an `IOLoop` cannot survive a fork or be shared across\n    processes in any way. When multiple processes are being used, each\n    process should create its own `IOLoop`, which also implies that\n    any objects which depend on the `IOLoop` (such as\n    `.AsyncHTTPClient`) must also be created in the child processes.\n    As a guideline, anything that starts processes (including the\n    `tornado.process` and `multiprocessing` modules) should do so as\n    early as possible, ideally the first thing the application does\n    after loading its configuration in ``main()``.\n\n    .. versionchanged:: 4.2\n       Added the ``make_current`` keyword argument to the `IOLoop`\n       constructor.\n\n    .. versionchanged:: 5.0\n\n       Uses the `asyncio` event loop by default. The\n       ``IOLoop.configure`` method cannot be used on Python 3 except\n       to redundantly specify the `asyncio` event loop.\n\n    \"\"\"\n    # Constants from the epoll module\n    _EPOLLIN = 0x001\n    _EPOLLPRI = 0x002\n    _EPOLLOUT = 0x004\n    _EPOLLERR = 0x008\n    _EPOLLHUP = 0x010\n    _EPOLLRDHUP = 0x2000\n    _EPOLLONESHOT = (1 << 30)\n    _EPOLLET = (1 << 31)\n\n    # Our events map exactly to the epoll events\n    NONE = 0\n    READ = _EPOLLIN\n    WRITE = _EPOLLOUT\n    ERROR = _EPOLLERR | _EPOLLHUP\n\n    # In Python 2, _current.instance points to the current IOLoop.\n    _current = threading.local()\n\n    # In Python 3, _ioloop_for_asyncio maps from asyncio loops to IOLoops.\n    _ioloop_for_asyncio = dict()\n\n    @classmethod\n    def configure(cls, impl, **kwargs):\n        if asyncio is not None:\n            from tornado.platform.asyncio import BaseAsyncIOLoop\n\n            if isinstance(impl, (str, unicode_type)):\n                impl = import_object(impl)\n            if not issubclass(impl, BaseAsyncIOLoop):\n                raise RuntimeError(\n                    \"only AsyncIOLoop is allowed when asyncio is available\")\n        super(IOLoop, cls).configure(impl, **kwargs)\n\n    @staticmethod\n    def instance():\n        \"\"\"Deprecated alias for `IOLoop.current()`.\n\n        .. versionchanged:: 5.0\n\n           Previously, this method returned a global singleton\n           `IOLoop`, in contrast with the per-thread `IOLoop` returned\n           by `current()`. In nearly all cases the two were the same\n           (when they differed, it was generally used from non-Tornado\n           threads to communicate back to the main thread's `IOLoop`).\n           This distinction is not present in `asyncio`, so in order\n           to facilitate integration with that package `instance()`\n           was changed to be an alias to `current()`. Applications\n           using the cross-thread communications aspect of\n           `instance()` should instead set their own global variable\n           to point to the `IOLoop` they want to use.\n\n        .. deprecated:: 5.0\n        \"\"\"\n        return IOLoop.current()\n\n    def install(self):\n        \"\"\"Deprecated alias for `make_current()`.\n\n        .. versionchanged:: 5.0\n\n           Previously, this method would set this `IOLoop` as the\n           global singleton used by `IOLoop.instance()`. Now that\n           `instance()` is an alias for `current()`, `install()`\n           is an alias for `make_current()`.\n\n        .. deprecated:: 5.0\n        \"\"\"\n        self.make_current()\n\n    @staticmethod\n    def clear_instance():\n        \"\"\"Deprecated alias for `clear_current()`.\n\n        .. versionchanged:: 5.0\n\n           Previously, this method would clear the `IOLoop` used as\n           the global singleton by `IOLoop.instance()`. Now that\n           `instance()` is an alias for `current()`,\n           `clear_instance()` is an alias for `clear_current()`.\n\n        .. deprecated:: 5.0\n\n        \"\"\"\n        IOLoop.clear_current()\n\n    @staticmethod\n    def current(instance=True):\n        \"\"\"Returns the current thread's `IOLoop`.\n\n        If an `IOLoop` is currently running or has been marked as\n        current by `make_current`, returns that instance.  If there is\n        no current `IOLoop` and ``instance`` is true, creates one.\n\n        .. versionchanged:: 4.1\n           Added ``instance`` argument to control the fallback to\n           `IOLoop.instance()`.\n        .. versionchanged:: 5.0\n           On Python 3, control of the current `IOLoop` is delegated\n           to `asyncio`, with this and other methods as pass-through accessors.\n           The ``instance`` argument now controls whether an `IOLoop`\n           is created automatically when there is none, instead of\n           whether we fall back to `IOLoop.instance()` (which is now\n           an alias for this method). ``instance=False`` is deprecated,\n           since even if we do not create an `IOLoop`, this method\n           may initialize the asyncio loop.\n        \"\"\"\n        if asyncio is None:\n            current = getattr(IOLoop._current, \"instance\", None)\n            if current is None and instance:\n                current = IOLoop()\n                if IOLoop._current.instance is not current:\n                    raise RuntimeError(\"new IOLoop did not become current\")\n        else:\n            try:\n                loop = asyncio.get_event_loop()\n            except (RuntimeError, AssertionError):\n                if not instance:\n                    return None\n                raise\n            try:\n                return IOLoop._ioloop_for_asyncio[loop]\n            except KeyError:\n                if instance:\n                    from tornado.platform.asyncio import AsyncIOMainLoop\n                    current = AsyncIOMainLoop(make_current=True)\n                else:\n                    current = None\n        return current\n\n    def make_current(self):\n        \"\"\"Makes this the `IOLoop` for the current thread.\n\n        An `IOLoop` automatically becomes current for its thread\n        when it is started, but it is sometimes useful to call\n        `make_current` explicitly before starting the `IOLoop`,\n        so that code run at startup time can find the right\n        instance.\n\n        .. versionchanged:: 4.1\n           An `IOLoop` created while there is no current `IOLoop`\n           will automatically become current.\n\n        .. versionchanged:: 5.0\n           This method also sets the current `asyncio` event loop.\n        \"\"\"\n        # The asyncio event loops override this method.\n        assert asyncio is None\n        old = getattr(IOLoop._current, \"instance\", None)\n        if old is not None:\n            old.clear_current()\n        IOLoop._current.instance = self\n\n    @staticmethod\n    def clear_current():\n        \"\"\"Clears the `IOLoop` for the current thread.\n\n        Intended primarily for use by test frameworks in between tests.\n\n        .. versionchanged:: 5.0\n           This method also clears the current `asyncio` event loop.\n        \"\"\"\n        old = IOLoop.current(instance=False)\n        if old is not None:\n            old._clear_current_hook()\n        if asyncio is None:\n            IOLoop._current.instance = None\n\n    def _clear_current_hook(self):\n        \"\"\"Instance method called when an IOLoop ceases to be current.\n\n        May be overridden by subclasses as a counterpart to make_current.\n        \"\"\"\n        pass\n\n    @classmethod\n    def configurable_base(cls):\n        return IOLoop\n\n    @classmethod\n    def configurable_default(cls):\n        if asyncio is not None:\n            from tornado.platform.asyncio import AsyncIOLoop\n            return AsyncIOLoop\n        return PollIOLoop\n\n    def initialize(self, make_current=None):\n        if make_current is None:\n            if IOLoop.current(instance=False) is None:\n                self.make_current()\n        elif make_current:\n            current = IOLoop.current(instance=False)\n            # AsyncIO loops can already be current by this point.\n            if current is not None and current is not self:\n                raise RuntimeError(\"current IOLoop already exists\")\n            self.make_current()\n\n    def close(self, all_fds=False):\n        \"\"\"Closes the `IOLoop`, freeing any resources used.\n\n        If ``all_fds`` is true, all file descriptors registered on the\n        IOLoop will be closed (not just the ones created by the\n        `IOLoop` itself).\n\n        Many applications will only use a single `IOLoop` that runs for the\n        entire lifetime of the process.  In that case closing the `IOLoop`\n        is not necessary since everything will be cleaned up when the\n        process exits.  `IOLoop.close` is provided mainly for scenarios\n        such as unit tests, which create and destroy a large number of\n        ``IOLoops``.\n\n        An `IOLoop` must be completely stopped before it can be closed.  This\n        means that `IOLoop.stop()` must be called *and* `IOLoop.start()` must\n        be allowed to return before attempting to call `IOLoop.close()`.\n        Therefore the call to `close` will usually appear just after\n        the call to `start` rather than near the call to `stop`.\n\n        .. versionchanged:: 3.1\n           If the `IOLoop` implementation supports non-integer objects\n           for \"file descriptors\", those objects will have their\n           ``close`` method when ``all_fds`` is true.\n        \"\"\"\n        raise NotImplementedError()\n\n    def add_handler(self, fd, handler, events):\n        \"\"\"Registers the given handler to receive the given events for ``fd``.\n\n        The ``fd`` argument may either be an integer file descriptor or\n        a file-like object with a ``fileno()`` method (and optionally a\n        ``close()`` method, which may be called when the `IOLoop` is shut\n        down).\n\n        The ``events`` argument is a bitwise or of the constants\n        ``IOLoop.READ``, ``IOLoop.WRITE``, and ``IOLoop.ERROR``.\n\n        When an event occurs, ``handler(fd, events)`` will be run.\n\n        .. versionchanged:: 4.0\n           Added the ability to pass file-like objects in addition to\n           raw file descriptors.\n        \"\"\"\n        raise NotImplementedError()\n\n    def update_handler(self, fd, events):\n        \"\"\"Changes the events we listen for ``fd``.\n\n        .. versionchanged:: 4.0\n           Added the ability to pass file-like objects in addition to\n           raw file descriptors.\n        \"\"\"\n        raise NotImplementedError()\n\n    def remove_handler(self, fd):\n        \"\"\"Stop listening for events on ``fd``.\n\n        .. versionchanged:: 4.0\n           Added the ability to pass file-like objects in addition to\n           raw file descriptors.\n        \"\"\"\n        raise NotImplementedError()\n\n    def set_blocking_signal_threshold(self, seconds, action):\n        \"\"\"Sends a signal if the `IOLoop` is blocked for more than\n        ``s`` seconds.\n\n        Pass ``seconds=None`` to disable.  Requires Python 2.6 on a unixy\n        platform.\n\n        The action parameter is a Python signal handler.  Read the\n        documentation for the `signal` module for more information.\n        If ``action`` is None, the process will be killed if it is\n        blocked for too long.\n\n        .. deprecated:: 5.0\n\n           Not implemented on the `asyncio` event loop. Use the environment\n           variable ``PYTHONASYNCIODEBUG=1`` instead.\n        \"\"\"\n        raise NotImplementedError()\n\n    def set_blocking_log_threshold(self, seconds):\n        \"\"\"Logs a stack trace if the `IOLoop` is blocked for more than\n        ``s`` seconds.\n\n        Equivalent to ``set_blocking_signal_threshold(seconds,\n        self.log_stack)``\n\n        .. deprecated:: 5.0\n\n           Not implemented on the `asyncio` event loop. Use the environment\n           variable ``PYTHONASYNCIODEBUG=1`` instead.\n        \"\"\"\n        self.set_blocking_signal_threshold(seconds, self.log_stack)\n\n    def log_stack(self, signal, frame):\n        \"\"\"Signal handler to log the stack trace of the current thread.\n\n        For use with `set_blocking_signal_threshold`.\n        \"\"\"\n        gen_log.warning('IOLoop blocked for %f seconds in\\n%s',\n                        self._blocking_signal_threshold,\n                        ''.join(traceback.format_stack(frame)))\n\n    def start(self):\n        \"\"\"Starts the I/O loop.\n\n        The loop will run until one of the callbacks calls `stop()`, which\n        will make the loop stop after the current event iteration completes.\n        \"\"\"\n        raise NotImplementedError()\n\n    def _setup_logging(self):\n        \"\"\"The IOLoop catches and logs exceptions, so it's\n        important that log output be visible.  However, python's\n        default behavior for non-root loggers (prior to python\n        3.2) is to print an unhelpful \"no handlers could be\n        found\" message rather than the actual log entry, so we\n        must explicitly configure logging if we've made it this\n        far without anything.\n\n        This method should be called from start() in subclasses.\n        \"\"\"\n        if not any([logging.getLogger().handlers,\n                    logging.getLogger('tornado').handlers,\n                    logging.getLogger('tornado.application').handlers]):\n            logging.basicConfig()\n\n    def stop(self):\n        \"\"\"Stop the I/O loop.\n\n        If the event loop is not currently running, the next call to `start()`\n        will return immediately.\n\n        To use asynchronous methods from otherwise-synchronous code (such as\n        unit tests), you can start and stop the event loop like this::\n\n          ioloop = IOLoop()\n          async_method(ioloop=ioloop, callback=ioloop.stop)\n          ioloop.start()\n\n        ``ioloop.start()`` will return after ``async_method`` has run\n        its callback, whether that callback was invoked before or\n        after ``ioloop.start``.\n\n        Note that even after `stop` has been called, the `IOLoop` is not\n        completely stopped until `IOLoop.start` has also returned.\n        Some work that was scheduled before the call to `stop` may still\n        be run before the `IOLoop` shuts down.\n        \"\"\"\n        raise NotImplementedError()\n\n    def run_sync(self, func, timeout=None):\n        \"\"\"Starts the `IOLoop`, runs the given function, and stops the loop.\n\n        The function must return either a yieldable object or\n        ``None``. If the function returns a yieldable object, the\n        `IOLoop` will run until the yieldable is resolved (and\n        `run_sync()` will return the yieldable's result). If it raises\n        an exception, the `IOLoop` will stop and the exception will be\n        re-raised to the caller.\n\n        The keyword-only argument ``timeout`` may be used to set\n        a maximum duration for the function.  If the timeout expires,\n        a `tornado.util.TimeoutError` is raised.\n\n        This method is useful in conjunction with `tornado.gen.coroutine`\n        to allow asynchronous calls in a ``main()`` function::\n\n            @gen.coroutine\n            def main():\n                # do stuff...\n\n            if __name__ == '__main__':\n                IOLoop.current().run_sync(main)\n\n        .. versionchanged:: 4.3\n           Returning a non-``None``, non-yieldable value is now an error.\n\n        .. versionchanged:: 5.0\n           If a timeout occurs, the ``func`` coroutine will be cancelled.\n        \"\"\"\n        future_cell = [None]\n\n        def run():\n            try:\n                result = func()\n                if result is not None:\n                    from tornado.gen import convert_yielded\n                    result = convert_yielded(result)\n            except Exception:\n                future_cell[0] = Future()\n                future_set_exc_info(future_cell[0], sys.exc_info())\n            else:\n                if is_future(result):\n                    future_cell[0] = result\n                else:\n                    future_cell[0] = Future()\n                    future_cell[0].set_result(result)\n            self.add_future(future_cell[0], lambda future: self.stop())\n        self.add_callback(run)\n        if timeout is not None:\n            def timeout_callback():\n                # If we can cancel the future, do so and wait on it. If not,\n                # Just stop the loop and return with the task still pending.\n                # (If we neither cancel nor wait for the task, a warning\n                # will be logged).\n                if not future_cell[0].cancel():\n                    self.stop()\n            timeout_handle = self.add_timeout(self.time() + timeout, timeout_callback)\n        self.start()\n        if timeout is not None:\n            self.remove_timeout(timeout_handle)\n        if future_cell[0].cancelled() or not future_cell[0].done():\n            raise TimeoutError('Operation timed out after %s seconds' % timeout)\n        return future_cell[0].result()\n\n    def time(self):\n        \"\"\"Returns the current time according to the `IOLoop`'s clock.\n\n        The return value is a floating-point number relative to an\n        unspecified time in the past.\n\n        By default, the `IOLoop`'s time function is `time.time`.  However,\n        it may be configured to use e.g. `time.monotonic` instead.\n        Calls to `add_timeout` that pass a number instead of a\n        `datetime.timedelta` should use this function to compute the\n        appropriate time, so they can work no matter what time function\n        is chosen.\n        \"\"\"\n        return time.time()\n\n    def add_timeout(self, deadline, callback, *args, **kwargs):\n        \"\"\"Runs the ``callback`` at the time ``deadline`` from the I/O loop.\n\n        Returns an opaque handle that may be passed to\n        `remove_timeout` to cancel.\n\n        ``deadline`` may be a number denoting a time (on the same\n        scale as `IOLoop.time`, normally `time.time`), or a\n        `datetime.timedelta` object for a deadline relative to the\n        current time.  Since Tornado 4.0, `call_later` is a more\n        convenient alternative for the relative case since it does not\n        require a timedelta object.\n\n        Note that it is not safe to call `add_timeout` from other threads.\n        Instead, you must use `add_callback` to transfer control to the\n        `IOLoop`'s thread, and then call `add_timeout` from there.\n\n        Subclasses of IOLoop must implement either `add_timeout` or\n        `call_at`; the default implementations of each will call\n        the other.  `call_at` is usually easier to implement, but\n        subclasses that wish to maintain compatibility with Tornado\n        versions prior to 4.0 must use `add_timeout` instead.\n\n        .. versionchanged:: 4.0\n           Now passes through ``*args`` and ``**kwargs`` to the callback.\n        \"\"\"\n        if isinstance(deadline, numbers.Real):\n            return self.call_at(deadline, callback, *args, **kwargs)\n        elif isinstance(deadline, datetime.timedelta):\n            return self.call_at(self.time() + timedelta_to_seconds(deadline),\n                                callback, *args, **kwargs)\n        else:\n            raise TypeError(\"Unsupported deadline %r\" % deadline)\n\n    def call_later(self, delay, callback, *args, **kwargs):\n        \"\"\"Runs the ``callback`` after ``delay`` seconds have passed.\n\n        Returns an opaque handle that may be passed to `remove_timeout`\n        to cancel.  Note that unlike the `asyncio` method of the same\n        name, the returned object does not have a ``cancel()`` method.\n\n        See `add_timeout` for comments on thread-safety and subclassing.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        return self.call_at(self.time() + delay, callback, *args, **kwargs)\n\n    def call_at(self, when, callback, *args, **kwargs):\n        \"\"\"Runs the ``callback`` at the absolute time designated by ``when``.\n\n        ``when`` must be a number using the same reference point as\n        `IOLoop.time`.\n\n        Returns an opaque handle that may be passed to `remove_timeout`\n        to cancel.  Note that unlike the `asyncio` method of the same\n        name, the returned object does not have a ``cancel()`` method.\n\n        See `add_timeout` for comments on thread-safety and subclassing.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        return self.add_timeout(when, callback, *args, **kwargs)\n\n    def remove_timeout(self, timeout):\n        \"\"\"Cancels a pending timeout.\n\n        The argument is a handle as returned by `add_timeout`.  It is\n        safe to call `remove_timeout` even if the callback has already\n        been run.\n        \"\"\"\n        raise NotImplementedError()\n\n    def add_callback(self, callback, *args, **kwargs):\n        \"\"\"Calls the given callback on the next I/O loop iteration.\n\n        It is safe to call this method from any thread at any time,\n        except from a signal handler.  Note that this is the **only**\n        method in `IOLoop` that makes this thread-safety guarantee; all\n        other interaction with the `IOLoop` must be done from that\n        `IOLoop`'s thread.  `add_callback()` may be used to transfer\n        control from other threads to the `IOLoop`'s thread.\n\n        To add a callback from a signal handler, see\n        `add_callback_from_signal`.\n        \"\"\"\n        raise NotImplementedError()\n\n    def add_callback_from_signal(self, callback, *args, **kwargs):\n        \"\"\"Calls the given callback on the next I/O loop iteration.\n\n        Safe for use from a Python signal handler; should not be used\n        otherwise.\n\n        Callbacks added with this method will be run without any\n        `.stack_context`, to avoid picking up the context of the function\n        that was interrupted by the signal.\n        \"\"\"\n        raise NotImplementedError()\n\n    def spawn_callback(self, callback, *args, **kwargs):\n        \"\"\"Calls the given callback on the next IOLoop iteration.\n\n        Unlike all other callback-related methods on IOLoop,\n        ``spawn_callback`` does not associate the callback with its caller's\n        ``stack_context``, so it is suitable for fire-and-forget callbacks\n        that should not interfere with the caller.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        with stack_context.NullContext():\n            self.add_callback(callback, *args, **kwargs)\n\n    def add_future(self, future, callback):\n        \"\"\"Schedules a callback on the ``IOLoop`` when the given\n        `.Future` is finished.\n\n        The callback is invoked with one argument, the\n        `.Future`.\n        \"\"\"\n        assert is_future(future)\n        callback = stack_context.wrap(callback)\n        future_add_done_callback(\n            future, lambda future: self.add_callback(callback, future))\n\n    def run_in_executor(self, executor, func, *args):\n        \"\"\"Runs a function in a ``concurrent.futures.Executor``. If\n        ``executor`` is ``None``, the IO loop's default executor will be used.\n\n        Use `functools.partial` to pass keyword arguments to ``func``.\n\n        .. versionadded:: 5.0\n        \"\"\"\n        if ThreadPoolExecutor is None:\n            raise RuntimeError(\n                \"concurrent.futures is required to use IOLoop.run_in_executor\")\n\n        if executor is None:\n            if not hasattr(self, '_executor'):\n                from tornado.process import cpu_count\n                self._executor = ThreadPoolExecutor(max_workers=(cpu_count() * 5))\n            executor = self._executor\n        c_future = executor.submit(func, *args)\n        # Concurrent Futures are not usable with await. Wrap this in a\n        # Tornado Future instead, using self.add_future for thread-safety.\n        t_future = Future()\n        self.add_future(c_future, lambda f: chain_future(f, t_future))\n        return t_future\n\n    def set_default_executor(self, executor):\n        \"\"\"Sets the default executor to use with :meth:`run_in_executor`.\n\n        .. versionadded:: 5.0\n        \"\"\"\n        self._executor = executor\n\n    def _run_callback(self, callback):\n        \"\"\"Runs a callback with error handling.\n\n        For use in subclasses.\n        \"\"\"\n        try:\n            ret = callback()\n            if ret is not None:\n                from tornado import gen\n                # Functions that return Futures typically swallow all\n                # exceptions and store them in the Future.  If a Future\n                # makes it out to the IOLoop, ensure its exception (if any)\n                # gets logged too.\n                try:\n                    ret = gen.convert_yielded(ret)\n                except gen.BadYieldError:\n                    # It's not unusual for add_callback to be used with\n                    # methods returning a non-None and non-yieldable\n                    # result, which should just be ignored.\n                    pass\n                else:\n                    self.add_future(ret, self._discard_future_result)\n        except Exception:\n            self.handle_callback_exception(callback)\n\n    def _discard_future_result(self, future):\n        \"\"\"Avoid unhandled-exception warnings from spawned coroutines.\"\"\"\n        future.result()\n\n    def handle_callback_exception(self, callback):\n        \"\"\"This method is called whenever a callback run by the `IOLoop`\n        throws an exception.\n\n        By default simply logs the exception as an error.  Subclasses\n        may override this method to customize reporting of exceptions.\n\n        The exception itself is not passed explicitly, but is available\n        in `sys.exc_info`.\n        \"\"\"\n        app_log.error(\"Exception in callback %r\", callback, exc_info=True)\n\n    def split_fd(self, fd):\n        \"\"\"Returns an (fd, obj) pair from an ``fd`` parameter.\n\n        We accept both raw file descriptors and file-like objects as\n        input to `add_handler` and related methods.  When a file-like\n        object is passed, we must retain the object itself so we can\n        close it correctly when the `IOLoop` shuts down, but the\n        poller interfaces favor file descriptors (they will accept\n        file-like objects and call ``fileno()`` for you, but they\n        always return the descriptor itself).\n\n        This method is provided for use by `IOLoop` subclasses and should\n        not generally be used by application code.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        try:\n            return fd.fileno(), fd\n        except AttributeError:\n            return fd, fd\n\n    def close_fd(self, fd):\n        \"\"\"Utility method to close an ``fd``.\n\n        If ``fd`` is a file-like object, we close it directly; otherwise\n        we use `os.close`.\n\n        This method is provided for use by `IOLoop` subclasses (in\n        implementations of ``IOLoop.close(all_fds=True)`` and should\n        not generally be used by application code.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        try:\n            try:\n                fd.close()\n            except AttributeError:\n                os.close(fd)\n        except OSError:\n            pass\n\n\nclass PollIOLoop(IOLoop):\n    \"\"\"Base class for IOLoops built around a select-like function.\n\n    For concrete implementations, see `tornado.platform.epoll.EPollIOLoop`\n    (Linux), `tornado.platform.kqueue.KQueueIOLoop` (BSD and Mac), or\n    `tornado.platform.select.SelectIOLoop` (all platforms).\n    \"\"\"\n    def initialize(self, impl, time_func=None, **kwargs):\n        super(PollIOLoop, self).initialize(**kwargs)\n        self._impl = impl\n        if hasattr(self._impl, 'fileno'):\n            set_close_exec(self._impl.fileno())\n        self.time_func = time_func or time.time\n        self._handlers = {}\n        self._events = {}\n        self._callbacks = collections.deque()\n        self._timeouts = []\n        self._cancellations = 0\n        self._running = False\n        self._stopped = False\n        self._closing = False\n        self._thread_ident = None\n        self._pid = os.getpid()\n        self._blocking_signal_threshold = None\n        self._timeout_counter = itertools.count()\n\n        # Create a pipe that we send bogus data to when we want to wake\n        # the I/O loop when it is idle\n        self._waker = Waker()\n        self.add_handler(self._waker.fileno(),\n                         lambda fd, events: self._waker.consume(),\n                         self.READ)\n\n    @classmethod\n    def configurable_base(cls):\n        return PollIOLoop\n\n    @classmethod\n    def configurable_default(cls):\n        if hasattr(select, \"epoll\"):\n            from tornado.platform.epoll import EPollIOLoop\n            return EPollIOLoop\n        if hasattr(select, \"kqueue\"):\n            # Python 2.6+ on BSD or Mac\n            from tornado.platform.kqueue import KQueueIOLoop\n            return KQueueIOLoop\n        from tornado.platform.select import SelectIOLoop\n        return SelectIOLoop\n\n    def close(self, all_fds=False):\n        self._closing = True\n        self.remove_handler(self._waker.fileno())\n        if all_fds:\n            for fd, handler in list(self._handlers.values()):\n                self.close_fd(fd)\n        self._waker.close()\n        self._impl.close()\n        self._callbacks = None\n        self._timeouts = None\n        if hasattr(self, '_executor'):\n            self._executor.shutdown()\n\n    def add_handler(self, fd, handler, events):\n        fd, obj = self.split_fd(fd)\n        self._handlers[fd] = (obj, stack_context.wrap(handler))\n        self._impl.register(fd, events | self.ERROR)\n\n    def update_handler(self, fd, events):\n        fd, obj = self.split_fd(fd)\n        self._impl.modify(fd, events | self.ERROR)\n\n    def remove_handler(self, fd):\n        fd, obj = self.split_fd(fd)\n        self._handlers.pop(fd, None)\n        self._events.pop(fd, None)\n        try:\n            self._impl.unregister(fd)\n        except Exception:\n            gen_log.debug(\"Error deleting fd from IOLoop\", exc_info=True)\n\n    def set_blocking_signal_threshold(self, seconds, action):\n        if not hasattr(signal, \"setitimer\"):\n            gen_log.error(\"set_blocking_signal_threshold requires a signal module \"\n                          \"with the setitimer method\")\n            return\n        self._blocking_signal_threshold = seconds\n        if seconds is not None:\n            signal.signal(signal.SIGALRM,\n                          action if action is not None else signal.SIG_DFL)\n\n    def start(self):\n        if self._running:\n            raise RuntimeError(\"IOLoop is already running\")\n        if os.getpid() != self._pid:\n            raise RuntimeError(\"Cannot share PollIOLoops across processes\")\n        self._setup_logging()\n        if self._stopped:\n            self._stopped = False\n            return\n        old_current = IOLoop.current(instance=False)\n        if old_current is not self:\n            self.make_current()\n        self._thread_ident = thread.get_ident()\n        self._running = True\n\n        # signal.set_wakeup_fd closes a race condition in event loops:\n        # a signal may arrive at the beginning of select/poll/etc\n        # before it goes into its interruptible sleep, so the signal\n        # will be consumed without waking the select.  The solution is\n        # for the (C, synchronous) signal handler to write to a pipe,\n        # which will then be seen by select.\n        #\n        # In python's signal handling semantics, this only matters on the\n        # main thread (fortunately, set_wakeup_fd only works on the main\n        # thread and will raise a ValueError otherwise).\n        #\n        # If someone has already set a wakeup fd, we don't want to\n        # disturb it.  This is an issue for twisted, which does its\n        # SIGCHLD processing in response to its own wakeup fd being\n        # written to.  As long as the wakeup fd is registered on the IOLoop,\n        # the loop will still wake up and everything should work.\n        old_wakeup_fd = None\n        if hasattr(signal, 'set_wakeup_fd') and os.name == 'posix':\n            # requires python 2.6+, unix.  set_wakeup_fd exists but crashes\n            # the python process on windows.\n            try:\n                old_wakeup_fd = signal.set_wakeup_fd(self._waker.write_fileno())\n                if old_wakeup_fd != -1:\n                    # Already set, restore previous value.  This is a little racy,\n                    # but there's no clean get_wakeup_fd and in real use the\n                    # IOLoop is just started once at the beginning.\n                    signal.set_wakeup_fd(old_wakeup_fd)\n                    old_wakeup_fd = None\n            except ValueError:\n                # Non-main thread, or the previous value of wakeup_fd\n                # is no longer valid.\n                old_wakeup_fd = None\n\n        try:\n            while True:\n                # Prevent IO event starvation by delaying new callbacks\n                # to the next iteration of the event loop.\n                ncallbacks = len(self._callbacks)\n\n                # Add any timeouts that have come due to the callback list.\n                # Do not run anything until we have determined which ones\n                # are ready, so timeouts that call add_timeout cannot\n                # schedule anything in this iteration.\n                due_timeouts = []\n                if self._timeouts:\n                    now = self.time()\n                    while self._timeouts:\n                        if self._timeouts[0].callback is None:\n                            # The timeout was cancelled.  Note that the\n                            # cancellation check is repeated below for timeouts\n                            # that are cancelled by another timeout or callback.\n                            heapq.heappop(self._timeouts)\n                            self._cancellations -= 1\n                        elif self._timeouts[0].deadline <= now:\n                            due_timeouts.append(heapq.heappop(self._timeouts))\n                        else:\n                            break\n                    if (self._cancellations > 512 and\n                            self._cancellations > (len(self._timeouts) >> 1)):\n                        # Clean up the timeout queue when it gets large and it's\n                        # more than half cancellations.\n                        self._cancellations = 0\n                        self._timeouts = [x for x in self._timeouts\n                                          if x.callback is not None]\n                        heapq.heapify(self._timeouts)\n\n                for i in range(ncallbacks):\n                    self._run_callback(self._callbacks.popleft())\n                for timeout in due_timeouts:\n                    if timeout.callback is not None:\n                        self._run_callback(timeout.callback)\n                # Closures may be holding on to a lot of memory, so allow\n                # them to be freed before we go into our poll wait.\n                due_timeouts = timeout = None\n\n                if self._callbacks:\n                    # If any callbacks or timeouts called add_callback,\n                    # we don't want to wait in poll() before we run them.\n                    poll_timeout = 0.0\n                elif self._timeouts:\n                    # If there are any timeouts, schedule the first one.\n                    # Use self.time() instead of 'now' to account for time\n                    # spent running callbacks.\n                    poll_timeout = self._timeouts[0].deadline - self.time()\n                    poll_timeout = max(0, min(poll_timeout, _POLL_TIMEOUT))\n                else:\n                    # No timeouts and no callbacks, so use the default.\n                    poll_timeout = _POLL_TIMEOUT\n\n                if not self._running:\n                    break\n\n                if self._blocking_signal_threshold is not None:\n                    # clear alarm so it doesn't fire while poll is waiting for\n                    # events.\n                    signal.setitimer(signal.ITIMER_REAL, 0, 0)\n\n                try:\n                    event_pairs = self._impl.poll(poll_timeout)\n                except Exception as e:\n                    # Depending on python version and IOLoop implementation,\n                    # different exception types may be thrown and there are\n                    # two ways EINTR might be signaled:\n                    # * e.errno == errno.EINTR\n                    # * e.args is like (errno.EINTR, 'Interrupted system call')\n                    if errno_from_exception(e) == errno.EINTR:\n                        continue\n                    else:\n                        raise\n\n                if self._blocking_signal_threshold is not None:\n                    signal.setitimer(signal.ITIMER_REAL,\n                                     self._blocking_signal_threshold, 0)\n\n                # Pop one fd at a time from the set of pending fds and run\n                # its handler. Since that handler may perform actions on\n                # other file descriptors, there may be reentrant calls to\n                # this IOLoop that modify self._events\n                self._events.update(event_pairs)\n                while self._events:\n                    fd, events = self._events.popitem()\n                    try:\n                        fd_obj, handler_func = self._handlers[fd]\n                        handler_func(fd_obj, events)\n                    except (OSError, IOError) as e:\n                        if errno_from_exception(e) == errno.EPIPE:\n                            # Happens when the client closes the connection\n                            pass\n                        else:\n                            self.handle_callback_exception(self._handlers.get(fd))\n                    except Exception:\n                        self.handle_callback_exception(self._handlers.get(fd))\n                fd_obj = handler_func = None\n\n        finally:\n            # reset the stopped flag so another start/stop pair can be issued\n            self._stopped = False\n            if self._blocking_signal_threshold is not None:\n                signal.setitimer(signal.ITIMER_REAL, 0, 0)\n            if old_current is None:\n                IOLoop.clear_current()\n            elif old_current is not self:\n                old_current.make_current()\n            if old_wakeup_fd is not None:\n                signal.set_wakeup_fd(old_wakeup_fd)\n\n    def stop(self):\n        self._running = False\n        self._stopped = True\n        self._waker.wake()\n\n    def time(self):\n        return self.time_func()\n\n    def call_at(self, deadline, callback, *args, **kwargs):\n        timeout = _Timeout(\n            deadline,\n            functools.partial(stack_context.wrap(callback), *args, **kwargs),\n            self)\n        heapq.heappush(self._timeouts, timeout)\n        return timeout\n\n    def remove_timeout(self, timeout):\n        # Removing from a heap is complicated, so just leave the defunct\n        # timeout object in the queue (see discussion in\n        # http://docs.python.org/library/heapq.html).\n        # If this turns out to be a problem, we could add a garbage\n        # collection pass whenever there are too many dead timeouts.\n        timeout.callback = None\n        self._cancellations += 1\n\n    def add_callback(self, callback, *args, **kwargs):\n        if self._closing:\n            return\n        # Blindly insert into self._callbacks. This is safe even\n        # from signal handlers because deque.append is atomic.\n        self._callbacks.append(functools.partial(\n            stack_context.wrap(callback), *args, **kwargs))\n        if thread.get_ident() != self._thread_ident:\n            # This will write one byte but Waker.consume() reads many\n            # at once, so it's ok to write even when not strictly\n            # necessary.\n            self._waker.wake()\n        else:\n            # If we're on the IOLoop's thread, we don't need to wake anyone.\n            pass\n\n    def add_callback_from_signal(self, callback, *args, **kwargs):\n        with stack_context.NullContext():\n            self.add_callback(callback, *args, **kwargs)\n\n\nclass _Timeout(object):\n    \"\"\"An IOLoop timeout, a UNIX timestamp and a callback\"\"\"\n\n    # Reduce memory overhead when there are lots of pending callbacks\n    __slots__ = ['deadline', 'callback', 'tdeadline']\n\n    def __init__(self, deadline, callback, io_loop):\n        if not isinstance(deadline, numbers.Real):\n            raise TypeError(\"Unsupported deadline %r\" % deadline)\n        self.deadline = deadline\n        self.callback = callback\n        self.tdeadline = (deadline, next(io_loop._timeout_counter))\n\n    # Comparison methods to sort by deadline, with object id as a tiebreaker\n    # to guarantee a consistent ordering.  The heapq module uses __le__\n    # in python2.5, and __lt__ in 2.6+ (sort() and most other comparisons\n    # use __lt__).\n    def __lt__(self, other):\n        return self.tdeadline < other.tdeadline\n\n    def __le__(self, other):\n        return self.tdeadline <= other.tdeadline\n\n\nclass PeriodicCallback(object):\n    \"\"\"Schedules the given callback to be called periodically.\n\n    The callback is called every ``callback_time`` milliseconds.\n    Note that the timeout is given in milliseconds, while most other\n    time-related functions in Tornado use seconds.\n\n    If the callback runs for longer than ``callback_time`` milliseconds,\n    subsequent invocations will be skipped to get back on schedule.\n\n    `start` must be called after the `PeriodicCallback` is created.\n\n    .. versionchanged:: 5.0\n       The ``io_loop`` argument (deprecated since version 4.1) has been removed.\n    \"\"\"\n    def __init__(self, callback, callback_time):\n        self.callback = callback\n        if callback_time <= 0:\n            raise ValueError(\"Periodic callback must have a positive callback_time\")\n        self.callback_time = callback_time\n        self._running = False\n        self._timeout = None\n\n    def start(self):\n        \"\"\"Starts the timer.\"\"\"\n        # Looking up the IOLoop here allows to first instantiate the\n        # PeriodicCallback in another thread, then start it using\n        # IOLoop.add_callback().\n        self.io_loop = IOLoop.current()\n        self._running = True\n        self._next_timeout = self.io_loop.time()\n        self._schedule_next()\n\n    def stop(self):\n        \"\"\"Stops the timer.\"\"\"\n        self._running = False\n        if self._timeout is not None:\n            self.io_loop.remove_timeout(self._timeout)\n            self._timeout = None\n\n    def is_running(self):\n        \"\"\"Return True if this `.PeriodicCallback` has been started.\n\n        .. versionadded:: 4.1\n        \"\"\"\n        return self._running\n\n    def _run(self):\n        if not self._running:\n            return\n        try:\n            return self.callback()\n        except Exception:\n            self.io_loop.handle_callback_exception(self.callback)\n        finally:\n            self._schedule_next()\n\n    def _schedule_next(self):\n        if self._running:\n            self._update_next(self.io_loop.time())\n            self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run)\n\n    def _update_next(self, current_time):\n        if self._next_timeout <= current_time:\n            callback_time_sec = self.callback_time / 1000.0\n            self._next_timeout += (math.floor((current_time - self._next_timeout) /\n                                              callback_time_sec) + 1) * callback_time_sec\n",
            "header": {
                "file": {
                    "path": "tornado/ioloop.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "f6ec177b",
                "new_commit_hash": "45d2d223",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/ioloop.py"
            },
            "plus_file": {
                "path": "b/tornado/ioloop.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 1213,
                            "length": 11
                        },
                        "new_range": {
                            "start": 1213,
                            "length": 11
                        },
                        "section": "class PeriodicCallback(object):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def _schedule_next(self):",
                                "type": "context"
                            },
                            {
                                "content": "        if self._running:",
                                "type": "context"
                            },
                            {
                                "content": "            current_time = self.io_loop.time()",
                                "type": "deleted"
                            },
                            {
                                "content": "",
                                "type": "deleted"
                            },
                            {
                                "content": "            if self._next_timeout <= current_time:",
                                "type": "deleted"
                            },
                            {
                                "content": "                callback_time_sec = self.callback_time / 1000.0",
                                "type": "deleted"
                            },
                            {
                                "content": "                self._next_timeout += (math.floor((current_time - self._next_timeout) /",
                                "type": "deleted"
                            },
                            {
                                "content": "                                                  callback_time_sec) + 1) * callback_time_sec",
                                "type": "deleted"
                            },
                            {
                                "content": "",
                                "type": "deleted"
                            },
                            {
                                "content": "            self._update_next(self.io_loop.time())",
                                "type": "added"
                            },
                            {
                                "content": "            self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def _update_next(self, current_time):",
                                "type": "added"
                            },
                            {
                                "content": "        if self._next_timeout <= current_time:",
                                "type": "added"
                            },
                            {
                                "content": "            callback_time_sec = self.callback_time / 1000.0",
                                "type": "added"
                            },
                            {
                                "content": "            self._next_timeout += (math.floor((current_time - self._next_timeout) /",
                                "type": "added"
                            },
                            {
                                "content": "                                              callback_time_sec) + 1) * callback_time_sec",
                                "type": "added"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/ioloop.py",
                            "type": "class",
                            "name": "PeriodicCallback",
                            "content": "class PeriodicCallback(object):\n    \"\"\"Schedules the given callback to be called periodically.\n\n    The callback is called every ``callback_time`` milliseconds.\n    Note that the timeout is given in milliseconds, while most other\n    time-related functions in Tornado use seconds.\n\n    If the callback runs for longer than ``callback_time`` milliseconds,\n    subsequent invocations will be skipped to get back on schedule.\n\n    `start` must be called after the `PeriodicCallback` is created.\n\n    .. versionchanged:: 5.0\n       The ``io_loop`` argument (deprecated since version 4.1) has been removed.\n    \"\"\"\n    def __init__(self, callback, callback_time):\n        self.callback = callback\n        if callback_time <= 0:\n            raise ValueError(\"Periodic callback must have a positive callback_time\")\n        self.callback_time = callback_time\n        self._running = False\n        self._timeout = None\n\n    def start(self):\n        \"\"\"Starts the timer.\"\"\"\n        # Looking up the IOLoop here allows to first instantiate the\n        # PeriodicCallback in another thread, then start it using\n        # IOLoop.add_callback().\n        self.io_loop = IOLoop.current()\n        self._running = True\n        self._next_timeout = self.io_loop.time()\n        self._schedule_next()\n\n    def stop(self):\n        \"\"\"Stops the timer.\"\"\"\n        self._running = False\n        if self._timeout is not None:\n            self.io_loop.remove_timeout(self._timeout)\n            self._timeout = None\n\n    def is_running(self):\n        \"\"\"Return True if this `.PeriodicCallback` has been started.\n\n        .. versionadded:: 4.1\n        \"\"\"\n        return self._running\n\n    def _run(self):\n        if not self._running:\n            return\n        try:\n            return self.callback()\n        except Exception:\n            self.io_loop.handle_callback_exception(self.callback)\n        finally:\n            self._schedule_next()\n\n    def _schedule_next(self):\n        if self._running:\n            current_time = self.io_loop.time()\n\n            if self._next_timeout <= current_time:\n                callback_time_sec = self.callback_time / 1000.0\n                self._next_timeout += (math.floor((current_time - self._next_timeout) /\n                                                  callback_time_sec) + 1) * callback_time_sec\n\n            self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 1157,
                            "end_lineno": 1223,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/ioloop.py",
                            "type": "method",
                            "name": "PeriodicCallback._schedule_next",
                            "content": "class PeriodicCallback(object):\n    \"\"\"Schedules the given callback to be called periodically.\n\n    The callback is called every ``callback_time`` milliseconds.\n    Note that the timeout is given in milliseconds, while most other\n    time-related functions in Tornado use seconds.\n\n    If the callback runs for longer than ``callback_time`` milliseconds,\n    subsequent invocations will be skipped to get back on schedule.\n\n    `start` must be called after the `PeriodicCallback` is created.\n\n    .. versionchanged:: 5.0\n       The ``io_loop`` argument (deprecated since version 4.1) has been removed.\n    \"\"\"\n    def __init__(self, callback, callback_time):\n        self.callback = callback\n        if callback_time <= 0:\n            raise ValueError(\"Periodic callback must have a positive callback_time\")\n        self.callback_time = callback_time\n        self._running = False\n        self._timeout = None\n\n    def start(self):\n        \"\"\"Starts the timer.\"\"\"\n        # Looking up the IOLoop here allows to first instantiate the\n        # PeriodicCallback in another thread, then start it using\n        # IOLoop.add_callback().\n        self.io_loop = IOLoop.current()\n        self._running = True\n        self._next_timeout = self.io_loop.time()\n        self._schedule_next()\n\n    def stop(self):\n        \"\"\"Stops the timer.\"\"\"\n        self._running = False\n        if self._timeout is not None:\n            self.io_loop.remove_timeout(self._timeout)\n            self._timeout = None\n\n    def is_running(self):\n        \"\"\"Return True if this `.PeriodicCallback` has been started.\n\n        .. versionadded:: 4.1\n        \"\"\"\n        return self._running\n\n    def _run(self):\n        if not self._running:\n            return\n        try:\n            return self.callback()\n        except Exception:\n            self.io_loop.handle_callback_exception(self.callback)\n        finally:\n            self._schedule_next()\n\n    def _schedule_next(self):\n        if self._running:\n            current_time = self.io_loop.time()\n\n            if self._next_timeout <= current_time:\n                callback_time_sec = self.callback_time / 1000.0\n                self._next_timeout += (math.floor((current_time - self._next_timeout) /\n                                                  callback_time_sec) + 1) * callback_time_sec\n\n            self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 1214,
                            "end_lineno": 1223,
                            "parent": {
                                "file_name": "tornado/ioloop.py",
                                "type": "class",
                                "name": "PeriodicCallback",
                                "content": "class PeriodicCallback(object):\n    \"\"\"Schedules the given callback to be called periodically.\n\n    The callback is called every ``callback_time`` milliseconds.\n    Note that the timeout is given in milliseconds, while most other\n    time-related functions in Tornado use seconds.\n\n    If the callback runs for longer than ``callback_time`` milliseconds,\n    subsequent invocations will be skipped to get back on schedule.\n\n    `start` must be called after the `PeriodicCallback` is created.\n\n    .. versionchanged:: 5.0\n       The ``io_loop`` argument (deprecated since version 4.1) has been removed.\n    \"\"\"\n    def __init__(self, callback, callback_time):\n        self.callback = callback\n        if callback_time <= 0:\n            raise ValueError(\"Periodic callback must have a positive callback_time\")\n        self.callback_time = callback_time\n        self._running = False\n        self._timeout = None\n\n    def start(self):\n        \"\"\"Starts the timer.\"\"\"\n        # Looking up the IOLoop here allows to first instantiate the\n        # PeriodicCallback in another thread, then start it using\n        # IOLoop.add_callback().\n        self.io_loop = IOLoop.current()\n        self._running = True\n        self._next_timeout = self.io_loop.time()\n        self._schedule_next()\n\n    def stop(self):\n        \"\"\"Stops the timer.\"\"\"\n        self._running = False\n        if self._timeout is not None:\n            self.io_loop.remove_timeout(self._timeout)\n            self._timeout = None\n\n    def is_running(self):\n        \"\"\"Return True if this `.PeriodicCallback` has been started.\n\n        .. versionadded:: 4.1\n        \"\"\"\n        return self._running\n\n    def _run(self):\n        if not self._running:\n            return\n        try:\n            return self.callback()\n        except Exception:\n            self.io_loop.handle_callback_exception(self.callback)\n        finally:\n            self._schedule_next()\n\n    def _schedule_next(self):\n        if self._running:\n            current_time = self.io_loop.time()\n\n            if self._next_timeout <= current_time:\n                callback_time_sec = self.callback_time / 1000.0\n                self._next_timeout += (math.floor((current_time - self._next_timeout) /\n                                                  callback_time_sec) + 1) * callback_time_sec\n\n            self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 1157,
                                "end_lineno": 1223,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "tornado/ioloop.py",
                            "type": "method",
                            "name": "PeriodicCallback._update_next",
                            "content": "class PeriodicCallback(object):\n    \"\"\"Schedules the given callback to be called periodically.\n\n    The callback is called every ``callback_time`` milliseconds.\n    Note that the timeout is given in milliseconds, while most other\n    time-related functions in Tornado use seconds.\n\n    If the callback runs for longer than ``callback_time`` milliseconds,\n    subsequent invocations will be skipped to get back on schedule.\n\n    `start` must be called after the `PeriodicCallback` is created.\n\n    .. versionchanged:: 5.0\n       The ``io_loop`` argument (deprecated since version 4.1) has been removed.\n    \"\"\"\n    def __init__(self, callback, callback_time):\n        self.callback = callback\n        if callback_time <= 0:\n            raise ValueError(\"Periodic callback must have a positive callback_time\")\n        self.callback_time = callback_time\n        self._running = False\n        self._timeout = None\n\n    def start(self):\n        \"\"\"Starts the timer.\"\"\"\n        # Looking up the IOLoop here allows to first instantiate the\n        # PeriodicCallback in another thread, then start it using\n        # IOLoop.add_callback().\n        self.io_loop = IOLoop.current()\n        self._running = True\n        self._next_timeout = self.io_loop.time()\n        self._schedule_next()\n\n    def stop(self):\n        \"\"\"Stops the timer.\"\"\"\n        self._running = False\n        if self._timeout is not None:\n            self.io_loop.remove_timeout(self._timeout)\n            self._timeout = None\n\n    def is_running(self):\n        \"\"\"Return True if this `.PeriodicCallback` has been started.\n\n        .. versionadded:: 4.1\n        \"\"\"\n        return self._running\n\n    def _run(self):\n        if not self._running:\n            return\n        try:\n            return self.callback()\n        except Exception:\n            self.io_loop.handle_callback_exception(self.callback)\n        finally:\n            self._schedule_next()\n\n    def _schedule_next(self):\n        if self._running:\n            self._update_next(self.io_loop.time())\n            self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run)\n\n    def _update_next(self, current_time):\n        if self._next_timeout <= current_time:\n            callback_time_sec = self.callback_time / 1000.0\n            self._next_timeout += (math.floor((current_time - self._next_timeout) /\n                                              callback_time_sec) + 1) * callback_time_sec",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 1219,
                            "end_lineno": 1223,
                            "parent": {
                                "file_name": "tornado/ioloop.py",
                                "type": "class",
                                "name": "PeriodicCallback",
                                "content": "class PeriodicCallback(object):\n    \"\"\"Schedules the given callback to be called periodically.\n\n    The callback is called every ``callback_time`` milliseconds.\n    Note that the timeout is given in milliseconds, while most other\n    time-related functions in Tornado use seconds.\n\n    If the callback runs for longer than ``callback_time`` milliseconds,\n    subsequent invocations will be skipped to get back on schedule.\n\n    `start` must be called after the `PeriodicCallback` is created.\n\n    .. versionchanged:: 5.0\n       The ``io_loop`` argument (deprecated since version 4.1) has been removed.\n    \"\"\"\n    def __init__(self, callback, callback_time):\n        self.callback = callback\n        if callback_time <= 0:\n            raise ValueError(\"Periodic callback must have a positive callback_time\")\n        self.callback_time = callback_time\n        self._running = False\n        self._timeout = None\n\n    def start(self):\n        \"\"\"Starts the timer.\"\"\"\n        # Looking up the IOLoop here allows to first instantiate the\n        # PeriodicCallback in another thread, then start it using\n        # IOLoop.add_callback().\n        self.io_loop = IOLoop.current()\n        self._running = True\n        self._next_timeout = self.io_loop.time()\n        self._schedule_next()\n\n    def stop(self):\n        \"\"\"Stops the timer.\"\"\"\n        self._running = False\n        if self._timeout is not None:\n            self.io_loop.remove_timeout(self._timeout)\n            self._timeout = None\n\n    def is_running(self):\n        \"\"\"Return True if this `.PeriodicCallback` has been started.\n\n        .. versionadded:: 4.1\n        \"\"\"\n        return self._running\n\n    def _run(self):\n        if not self._running:\n            return\n        try:\n            return self.callback()\n        except Exception:\n            self.io_loop.handle_callback_exception(self.callback)\n        finally:\n            self._schedule_next()\n\n    def _schedule_next(self):\n        if self._running:\n            self._update_next(self.io_loop.time())\n            self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run)\n\n    def _update_next(self, current_time):\n        if self._next_timeout <= current_time:\n            callback_time_sec = self.callback_time / 1000.0\n            self._next_timeout += (math.floor((current_time - self._next_timeout) /\n                                              callback_time_sec) + 1) * callback_time_sec",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 1157,
                                "end_lineno": 1223,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "from __future__ import absolute_import, division, print_function\n\nfrom concurrent.futures import ThreadPoolExecutor\nimport contextlib\nimport datetime\nimport functools\nimport socket\nimport subprocess\nimport sys\nimport threading\nimport time\nimport types\n\nfrom tornado.escape import native_str\nfrom tornado import gen\nfrom tornado.ioloop import IOLoop, TimeoutError, PollIOLoop, PeriodicCallback\nfrom tornado.log import app_log\nfrom tornado.platform.select import _Select\nfrom tornado.stack_context import ExceptionStackContext, StackContext, wrap, NullContext\nfrom tornado.testing import AsyncTestCase, bind_unused_port, ExpectLog, gen_test\nfrom tornado.test.util import unittest, skipIfNonUnix, skipOnTravis, skipBefore35, exec_test\n\ntry:\n    from concurrent import futures\nexcept ImportError:\n    futures = None\n\ntry:\n    import asyncio\nexcept ImportError:\n    asyncio = None\n\ntry:\n    import twisted\nexcept ImportError:\n    twisted = None\n\n\nclass FakeTimeSelect(_Select):\n    def __init__(self):\n        self._time = 1000\n        super(FakeTimeSelect, self).__init__()\n\n    def time(self):\n        return self._time\n\n    def sleep(self, t):\n        self._time += t\n\n    def poll(self, timeout):\n        events = super(FakeTimeSelect, self).poll(0)\n        if events:\n            return events\n        self._time += timeout\n        return []\n\n\nclass FakeTimeIOLoop(PollIOLoop):\n    \"\"\"IOLoop implementation with a fake and deterministic clock.\n\n    The clock advances as needed to trigger timeouts immediately.\n    For use when testing code that involves the passage of time\n    and no external dependencies.\n    \"\"\"\n    def initialize(self):\n        self.fts = FakeTimeSelect()\n        super(FakeTimeIOLoop, self).initialize(impl=self.fts,\n                                               time_func=self.fts.time)\n\n    def sleep(self, t):\n        \"\"\"Simulate a blocking sleep by advancing the clock.\"\"\"\n        self.fts.sleep(t)\n\n\nclass TestIOLoop(AsyncTestCase):\n    def test_add_callback_return_sequence(self):\n        # A callback returning {} or [] shouldn't spin the CPU, see Issue #1803.\n        self.calls = 0\n\n        loop = self.io_loop\n        test = self\n        old_add_callback = loop.add_callback\n\n        def add_callback(self, callback, *args, **kwargs):\n            test.calls += 1\n            old_add_callback(callback, *args, **kwargs)\n\n        loop.add_callback = types.MethodType(add_callback, loop)\n        loop.add_callback(lambda: {})\n        loop.add_callback(lambda: [])\n        loop.add_timeout(datetime.timedelta(milliseconds=50), loop.stop)\n        loop.start()\n        self.assertLess(self.calls, 10)\n\n    @skipOnTravis\n    def test_add_callback_wakeup(self):\n        # Make sure that add_callback from inside a running IOLoop\n        # wakes up the IOLoop immediately instead of waiting for a timeout.\n        def callback():\n            self.called = True\n            self.stop()\n\n        def schedule_callback():\n            self.called = False\n            self.io_loop.add_callback(callback)\n            # Store away the time so we can check if we woke up immediately\n            self.start_time = time.time()\n        self.io_loop.add_timeout(self.io_loop.time(), schedule_callback)\n        self.wait()\n        self.assertAlmostEqual(time.time(), self.start_time, places=2)\n        self.assertTrue(self.called)\n\n    @skipOnTravis\n    def test_add_callback_wakeup_other_thread(self):\n        def target():\n            # sleep a bit to let the ioloop go into its poll loop\n            time.sleep(0.01)\n            self.stop_time = time.time()\n            self.io_loop.add_callback(self.stop)\n        thread = threading.Thread(target=target)\n        self.io_loop.add_callback(thread.start)\n        self.wait()\n        delta = time.time() - self.stop_time\n        self.assertLess(delta, 0.1)\n        thread.join()\n\n    def test_add_timeout_timedelta(self):\n        self.io_loop.add_timeout(datetime.timedelta(microseconds=1), self.stop)\n        self.wait()\n\n    def test_multiple_add(self):\n        sock, port = bind_unused_port()\n        try:\n            self.io_loop.add_handler(sock.fileno(), lambda fd, events: None,\n                                     IOLoop.READ)\n            # Attempting to add the same handler twice fails\n            # (with a platform-dependent exception)\n            self.assertRaises(Exception, self.io_loop.add_handler,\n                              sock.fileno(), lambda fd, events: None,\n                              IOLoop.READ)\n        finally:\n            self.io_loop.remove_handler(sock.fileno())\n            sock.close()\n\n    def test_remove_without_add(self):\n        # remove_handler should not throw an exception if called on an fd\n        # was never added.\n        sock, port = bind_unused_port()\n        try:\n            self.io_loop.remove_handler(sock.fileno())\n        finally:\n            sock.close()\n\n    def test_add_callback_from_signal(self):\n        # cheat a little bit and just run this normally, since we can't\n        # easily simulate the races that happen with real signal handlers\n        self.io_loop.add_callback_from_signal(self.stop)\n        self.wait()\n\n    def test_add_callback_from_signal_other_thread(self):\n        # Very crude test, just to make sure that we cover this case.\n        # This also happens to be the first test where we run an IOLoop in\n        # a non-main thread.\n        other_ioloop = IOLoop()\n        thread = threading.Thread(target=other_ioloop.start)\n        thread.start()\n        other_ioloop.add_callback_from_signal(other_ioloop.stop)\n        thread.join()\n        other_ioloop.close()\n\n    def test_add_callback_while_closing(self):\n        # add_callback should not fail if it races with another thread\n        # closing the IOLoop. The callbacks are dropped silently\n        # without executing.\n        closing = threading.Event()\n\n        def target():\n            other_ioloop.add_callback(other_ioloop.stop)\n            other_ioloop.start()\n            closing.set()\n            other_ioloop.close(all_fds=True)\n        other_ioloop = IOLoop()\n        thread = threading.Thread(target=target)\n        thread.start()\n        closing.wait()\n        for i in range(1000):\n            other_ioloop.add_callback(lambda: None)\n\n    def test_handle_callback_exception(self):\n        # IOLoop.handle_callback_exception can be overridden to catch\n        # exceptions in callbacks.\n        def handle_callback_exception(callback):\n            self.assertIs(sys.exc_info()[0], ZeroDivisionError)\n            self.stop()\n        self.io_loop.handle_callback_exception = handle_callback_exception\n        with NullContext():\n            # remove the test StackContext that would see this uncaught\n            # exception as a test failure.\n            self.io_loop.add_callback(lambda: 1 / 0)\n        self.wait()\n\n    @skipIfNonUnix  # just because socketpair is so convenient\n    def test_read_while_writeable(self):\n        # Ensure that write events don't come in while we're waiting for\n        # a read and haven't asked for writeability. (the reverse is\n        # difficult to test for)\n        client, server = socket.socketpair()\n        try:\n            def handler(fd, events):\n                self.assertEqual(events, IOLoop.READ)\n                self.stop()\n            self.io_loop.add_handler(client.fileno(), handler, IOLoop.READ)\n            self.io_loop.add_timeout(self.io_loop.time() + 0.01,\n                                     functools.partial(server.send, b'asdf'))\n            self.wait()\n            self.io_loop.remove_handler(client.fileno())\n        finally:\n            client.close()\n            server.close()\n\n    def test_remove_timeout_after_fire(self):\n        # It is not an error to call remove_timeout after it has run.\n        handle = self.io_loop.add_timeout(self.io_loop.time(), self.stop)\n        self.wait()\n        self.io_loop.remove_timeout(handle)\n\n    def test_remove_timeout_cleanup(self):\n        # Add and remove enough callbacks to trigger cleanup.\n        # Not a very thorough test, but it ensures that the cleanup code\n        # gets executed and doesn't blow up.  This test is only really useful\n        # on PollIOLoop subclasses, but it should run silently on any\n        # implementation.\n        for i in range(2000):\n            timeout = self.io_loop.add_timeout(self.io_loop.time() + 3600,\n                                               lambda: None)\n            self.io_loop.remove_timeout(timeout)\n        # HACK: wait two IOLoop iterations for the GC to happen.\n        self.io_loop.add_callback(lambda: self.io_loop.add_callback(self.stop))\n        self.wait()\n\n    def test_remove_timeout_from_timeout(self):\n        calls = [False, False]\n\n        # Schedule several callbacks and wait for them all to come due at once.\n        # t2 should be cancelled by t1, even though it is already scheduled to\n        # be run before the ioloop even looks at it.\n        now = self.io_loop.time()\n\n        def t1():\n            calls[0] = True\n            self.io_loop.remove_timeout(t2_handle)\n        self.io_loop.add_timeout(now + 0.01, t1)\n\n        def t2():\n            calls[1] = True\n        t2_handle = self.io_loop.add_timeout(now + 0.02, t2)\n        self.io_loop.add_timeout(now + 0.03, self.stop)\n        time.sleep(0.03)\n        self.wait()\n        self.assertEqual(calls, [True, False])\n\n    def test_timeout_with_arguments(self):\n        # This tests that all the timeout methods pass through *args correctly.\n        results = []\n        self.io_loop.add_timeout(self.io_loop.time(), results.append, 1)\n        self.io_loop.add_timeout(datetime.timedelta(seconds=0),\n                                 results.append, 2)\n        self.io_loop.call_at(self.io_loop.time(), results.append, 3)\n        self.io_loop.call_later(0, results.append, 4)\n        self.io_loop.call_later(0, self.stop)\n        self.wait()\n        # The asyncio event loop does not guarantee the order of these\n        # callbacks, but PollIOLoop does.\n        self.assertEqual(sorted(results), [1, 2, 3, 4])\n\n    def test_add_timeout_return(self):\n        # All the timeout methods return non-None handles that can be\n        # passed to remove_timeout.\n        handle = self.io_loop.add_timeout(self.io_loop.time(), lambda: None)\n        self.assertFalse(handle is None)\n        self.io_loop.remove_timeout(handle)\n\n    def test_call_at_return(self):\n        handle = self.io_loop.call_at(self.io_loop.time(), lambda: None)\n        self.assertFalse(handle is None)\n        self.io_loop.remove_timeout(handle)\n\n    def test_call_later_return(self):\n        handle = self.io_loop.call_later(0, lambda: None)\n        self.assertFalse(handle is None)\n        self.io_loop.remove_timeout(handle)\n\n    def test_close_file_object(self):\n        \"\"\"When a file object is used instead of a numeric file descriptor,\n        the object should be closed (by IOLoop.close(all_fds=True),\n        not just the fd.\n        \"\"\"\n        # Use a socket since they are supported by IOLoop on all platforms.\n        # Unfortunately, sockets don't support the .closed attribute for\n        # inspecting their close status, so we must use a wrapper.\n        class SocketWrapper(object):\n            def __init__(self, sockobj):\n                self.sockobj = sockobj\n                self.closed = False\n\n            def fileno(self):\n                return self.sockobj.fileno()\n\n            def close(self):\n                self.closed = True\n                self.sockobj.close()\n        sockobj, port = bind_unused_port()\n        socket_wrapper = SocketWrapper(sockobj)\n        io_loop = IOLoop()\n        io_loop.add_handler(socket_wrapper, lambda fd, events: None,\n                            IOLoop.READ)\n        io_loop.close(all_fds=True)\n        self.assertTrue(socket_wrapper.closed)\n\n    def test_handler_callback_file_object(self):\n        \"\"\"The handler callback receives the same fd object it passed in.\"\"\"\n        server_sock, port = bind_unused_port()\n        fds = []\n\n        def handle_connection(fd, events):\n            fds.append(fd)\n            conn, addr = server_sock.accept()\n            conn.close()\n            self.stop()\n        self.io_loop.add_handler(server_sock, handle_connection, IOLoop.READ)\n        with contextlib.closing(socket.socket()) as client_sock:\n            client_sock.connect(('127.0.0.1', port))\n            self.wait()\n        self.io_loop.remove_handler(server_sock)\n        self.io_loop.add_handler(server_sock.fileno(), handle_connection,\n                                 IOLoop.READ)\n        with contextlib.closing(socket.socket()) as client_sock:\n            client_sock.connect(('127.0.0.1', port))\n            self.wait()\n        self.assertIs(fds[0], server_sock)\n        self.assertEqual(fds[1], server_sock.fileno())\n        self.io_loop.remove_handler(server_sock.fileno())\n        server_sock.close()\n\n    def test_mixed_fd_fileobj(self):\n        server_sock, port = bind_unused_port()\n\n        def f(fd, events):\n            pass\n        self.io_loop.add_handler(server_sock, f, IOLoop.READ)\n        with self.assertRaises(Exception):\n            # The exact error is unspecified - some implementations use\n            # IOError, others use ValueError.\n            self.io_loop.add_handler(server_sock.fileno(), f, IOLoop.READ)\n        self.io_loop.remove_handler(server_sock.fileno())\n        server_sock.close()\n\n    def test_reentrant(self):\n        \"\"\"Calling start() twice should raise an error, not deadlock.\"\"\"\n        returned_from_start = [False]\n        got_exception = [False]\n\n        def callback():\n            try:\n                self.io_loop.start()\n                returned_from_start[0] = True\n            except Exception:\n                got_exception[0] = True\n            self.stop()\n        self.io_loop.add_callback(callback)\n        self.wait()\n        self.assertTrue(got_exception[0])\n        self.assertFalse(returned_from_start[0])\n\n    def test_exception_logging(self):\n        \"\"\"Uncaught exceptions get logged by the IOLoop.\"\"\"\n        # Use a NullContext to keep the exception from being caught by\n        # AsyncTestCase.\n        with NullContext():\n            self.io_loop.add_callback(lambda: 1 / 0)\n            self.io_loop.add_callback(self.stop)\n            with ExpectLog(app_log, \"Exception in callback\"):\n                self.wait()\n\n    def test_exception_logging_future(self):\n        \"\"\"The IOLoop examines exceptions from Futures and logs them.\"\"\"\n        with NullContext():\n            @gen.coroutine\n            def callback():\n                self.io_loop.add_callback(self.stop)\n                1 / 0\n            self.io_loop.add_callback(callback)\n            with ExpectLog(app_log, \"Exception in callback\"):\n                self.wait()\n\n    @skipBefore35\n    def test_exception_logging_native_coro(self):\n        \"\"\"The IOLoop examines exceptions from awaitables and logs them.\"\"\"\n        namespace = exec_test(globals(), locals(), \"\"\"\n        async def callback():\n            # Stop the IOLoop two iterations after raising an exception\n            # to give the exception time to be logged.\n            self.io_loop.add_callback(self.io_loop.add_callback, self.stop)\n            1 / 0\n        \"\"\")\n        with NullContext():\n            self.io_loop.add_callback(namespace[\"callback\"])\n            with ExpectLog(app_log, \"Exception in callback\"):\n                self.wait()\n\n    def test_spawn_callback(self):\n        # An added callback runs in the test's stack_context, so will be\n        # re-raised in wait().\n        self.io_loop.add_callback(lambda: 1 / 0)\n        with self.assertRaises(ZeroDivisionError):\n            self.wait()\n        # A spawned callback is run directly on the IOLoop, so it will be\n        # logged without stopping the test.\n        self.io_loop.spawn_callback(lambda: 1 / 0)\n        self.io_loop.add_callback(self.stop)\n        with ExpectLog(app_log, \"Exception in callback\"):\n            self.wait()\n\n    @skipIfNonUnix\n    def test_remove_handler_from_handler(self):\n        # Create two sockets with simultaneous read events.\n        client, server = socket.socketpair()\n        try:\n            client.send(b'abc')\n            server.send(b'abc')\n\n            # After reading from one fd, remove the other from the IOLoop.\n            chunks = []\n\n            def handle_read(fd, events):\n                chunks.append(fd.recv(1024))\n                if fd is client:\n                    self.io_loop.remove_handler(server)\n                else:\n                    self.io_loop.remove_handler(client)\n            self.io_loop.add_handler(client, handle_read, self.io_loop.READ)\n            self.io_loop.add_handler(server, handle_read, self.io_loop.READ)\n            self.io_loop.call_later(0.1, self.stop)\n            self.wait()\n\n            # Only one fd was read; the other was cleanly removed.\n            self.assertEqual(chunks, [b'abc'])\n        finally:\n            client.close()\n            server.close()\n\n\n# Deliberately not a subclass of AsyncTestCase so the IOLoop isn't\n# automatically set as current.\nclass TestIOLoopCurrent(unittest.TestCase):\n    def setUp(self):\n        self.io_loop = None\n        IOLoop.clear_current()\n\n    def tearDown(self):\n        if self.io_loop is not None:\n            self.io_loop.close()\n\n    def test_default_current(self):\n        self.io_loop = IOLoop()\n        # The first IOLoop with default arguments is made current.\n        self.assertIs(self.io_loop, IOLoop.current())\n        # A second IOLoop can be created but is not made current.\n        io_loop2 = IOLoop()\n        self.assertIs(self.io_loop, IOLoop.current())\n        io_loop2.close()\n\n    def test_non_current(self):\n        self.io_loop = IOLoop(make_current=False)\n        # The new IOLoop is not initially made current.\n        self.assertIsNone(IOLoop.current(instance=False))\n        # Starting the IOLoop makes it current, and stopping the loop\n        # makes it non-current. This process is repeatable.\n        for i in range(3):\n            def f():\n                self.current_io_loop = IOLoop.current()\n                self.io_loop.stop()\n            self.io_loop.add_callback(f)\n            self.io_loop.start()\n            self.assertIs(self.current_io_loop, self.io_loop)\n            # Now that the loop is stopped, it is no longer current.\n            self.assertIsNone(IOLoop.current(instance=False))\n\n    def test_force_current(self):\n        self.io_loop = IOLoop(make_current=True)\n        self.assertIs(self.io_loop, IOLoop.current())\n        with self.assertRaises(RuntimeError):\n            # A second make_current=True construction cannot succeed.\n            IOLoop(make_current=True)\n        # current() was not affected by the failed construction.\n        self.assertIs(self.io_loop, IOLoop.current())\n\n\nclass TestIOLoopCurrentAsync(AsyncTestCase):\n    @gen_test\n    def test_clear_without_current(self):\n        # If there is no current IOLoop, clear_current is a no-op (but\n        # should not fail). Use a thread so we see the threading.Local\n        # in a pristine state.\n        with ThreadPoolExecutor(1) as e:\n            yield e.submit(IOLoop.clear_current)\n\n\nclass TestIOLoopAddCallback(AsyncTestCase):\n    def setUp(self):\n        super(TestIOLoopAddCallback, self).setUp()\n        self.active_contexts = []\n\n    def add_callback(self, callback, *args, **kwargs):\n        self.io_loop.add_callback(callback, *args, **kwargs)\n\n    @contextlib.contextmanager\n    def context(self, name):\n        self.active_contexts.append(name)\n        yield\n        self.assertEqual(self.active_contexts.pop(), name)\n\n    def test_pre_wrap(self):\n        # A pre-wrapped callback is run in the context in which it was\n        # wrapped, not when it was added to the IOLoop.\n        def f1():\n            self.assertIn('c1', self.active_contexts)\n            self.assertNotIn('c2', self.active_contexts)\n            self.stop()\n\n        with StackContext(functools.partial(self.context, 'c1')):\n            wrapped = wrap(f1)\n\n        with StackContext(functools.partial(self.context, 'c2')):\n            self.add_callback(wrapped)\n\n        self.wait()\n\n    def test_pre_wrap_with_args(self):\n        # Same as test_pre_wrap, but the function takes arguments.\n        # Implementation note: The function must not be wrapped in a\n        # functools.partial until after it has been passed through\n        # stack_context.wrap\n        def f1(foo, bar):\n            self.assertIn('c1', self.active_contexts)\n            self.assertNotIn('c2', self.active_contexts)\n            self.stop((foo, bar))\n\n        with StackContext(functools.partial(self.context, 'c1')):\n            wrapped = wrap(f1)\n\n        with StackContext(functools.partial(self.context, 'c2')):\n            self.add_callback(wrapped, 1, bar=2)\n\n        result = self.wait()\n        self.assertEqual(result, (1, 2))\n\n\nclass TestIOLoopAddCallbackFromSignal(TestIOLoopAddCallback):\n    # Repeat the add_callback tests using add_callback_from_signal\n    def add_callback(self, callback, *args, **kwargs):\n        self.io_loop.add_callback_from_signal(callback, *args, **kwargs)\n\n\n@unittest.skipIf(futures is None, \"futures module not present\")\nclass TestIOLoopFutures(AsyncTestCase):\n    def test_add_future_threads(self):\n        with futures.ThreadPoolExecutor(1) as pool:\n            self.io_loop.add_future(pool.submit(lambda: None),\n                                    lambda future: self.stop(future))\n            future = self.wait()\n            self.assertTrue(future.done())\n            self.assertTrue(future.result() is None)\n\n    def test_add_future_stack_context(self):\n        ready = threading.Event()\n\n        def task():\n            # we must wait for the ioloop callback to be scheduled before\n            # the task completes to ensure that add_future adds the callback\n            # asynchronously (which is the scenario in which capturing\n            # the stack_context matters)\n            ready.wait(1)\n            assert ready.isSet(), \"timed out\"\n            raise Exception(\"worker\")\n\n        def callback(future):\n            self.future = future\n            raise Exception(\"callback\")\n\n        def handle_exception(typ, value, traceback):\n            self.exception = value\n            self.stop()\n            return True\n\n        # stack_context propagates to the ioloop callback, but the worker\n        # task just has its exceptions caught and saved in the Future.\n        with futures.ThreadPoolExecutor(1) as pool:\n            with ExceptionStackContext(handle_exception):\n                self.io_loop.add_future(pool.submit(task), callback)\n            ready.set()\n        self.wait()\n\n        self.assertEqual(self.exception.args[0], \"callback\")\n        self.assertEqual(self.future.exception().args[0], \"worker\")\n\n    @gen_test\n    def test_run_in_executor_gen(self):\n        event1 = threading.Event()\n        event2 = threading.Event()\n\n        def sync_func(self_event, other_event):\n            self_event.set()\n            other_event.wait()\n            # Note that return value doesn't actually do anything,\n            # it is just passed through to our final assertion to\n            # make sure it is passed through properly.\n            return self_event\n\n        # Run two synchronous functions, which would deadlock if not\n        # run in parallel.\n        res = yield [\n            IOLoop.current().run_in_executor(None, sync_func, event1, event2),\n            IOLoop.current().run_in_executor(None, sync_func, event2, event1)\n        ]\n\n        self.assertEqual([event1, event2], res)\n\n    @skipBefore35\n    @gen_test\n    def test_run_in_executor_native(self):\n        event1 = threading.Event()\n        event2 = threading.Event()\n\n        def sync_func(self_event, other_event):\n            self_event.set()\n            other_event.wait()\n            return self_event\n\n        # Go through an async wrapper to ensure that the result of\n        # run_in_executor works with await and not just gen.coroutine\n        # (simply passing the underlying concurrrent future would do that).\n        namespace = exec_test(globals(), locals(), \"\"\"\n            async def async_wrapper(self_event, other_event):\n                return await IOLoop.current().run_in_executor(\n                    None, sync_func, self_event, other_event)\n        \"\"\")\n\n        res = yield [\n            namespace[\"async_wrapper\"](event1, event2),\n            namespace[\"async_wrapper\"](event2, event1)\n        ]\n\n        self.assertEqual([event1, event2], res)\n\n    @gen_test\n    def test_set_default_executor(self):\n        count = [0]\n\n        class MyExecutor(futures.ThreadPoolExecutor):\n            def submit(self, func, *args):\n                count[0] += 1\n                return super(MyExecutor, self).submit(func, *args)\n\n        event = threading.Event()\n\n        def sync_func():\n            event.set()\n\n        executor = MyExecutor(1)\n        loop = IOLoop.current()\n        loop.set_default_executor(executor)\n        yield loop.run_in_executor(None, sync_func)\n        self.assertEqual(1, count[0])\n        self.assertTrue(event.is_set())\n\n\nclass TestIOLoopRunSync(unittest.TestCase):\n    def setUp(self):\n        self.io_loop = IOLoop()\n\n    def tearDown(self):\n        self.io_loop.close()\n\n    def test_sync_result(self):\n        with self.assertRaises(gen.BadYieldError):\n            self.io_loop.run_sync(lambda: 42)\n\n    def test_sync_exception(self):\n        with self.assertRaises(ZeroDivisionError):\n            self.io_loop.run_sync(lambda: 1 / 0)\n\n    def test_async_result(self):\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            raise gen.Return(42)\n        self.assertEqual(self.io_loop.run_sync(f), 42)\n\n    def test_async_exception(self):\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            1 / 0\n        with self.assertRaises(ZeroDivisionError):\n            self.io_loop.run_sync(f)\n\n    def test_current(self):\n        def f():\n            self.assertIs(IOLoop.current(), self.io_loop)\n        self.io_loop.run_sync(f)\n\n    def test_timeout(self):\n        @gen.coroutine\n        def f():\n            yield gen.sleep(1)\n        self.assertRaises(TimeoutError, self.io_loop.run_sync, f, timeout=0.01)\n\n    @skipBefore35\n    def test_native_coroutine(self):\n        @gen.coroutine\n        def f1():\n            yield gen.moment\n\n        namespace = exec_test(globals(), locals(), \"\"\"\n        async def f2():\n            await f1()\n        \"\"\")\n        self.io_loop.run_sync(namespace['f2'])\n\n\n@unittest.skipIf(asyncio is not None,\n                 'IOLoop configuration not available')\nclass TestPeriodicCallback(unittest.TestCase):\n    def setUp(self):\n        self.io_loop = FakeTimeIOLoop()\n        self.io_loop.make_current()\n\n    def tearDown(self):\n        self.io_loop.close()\n\n    def test_basic(self):\n        calls = []\n\n        def cb():\n            calls.append(self.io_loop.time())\n        pc = PeriodicCallback(cb, 10000)\n        pc.start()\n        self.io_loop.call_later(50, self.io_loop.stop)\n        self.io_loop.start()\n        self.assertEqual(calls, [1010, 1020, 1030, 1040, 1050])\n\n    def test_overrun(self):\n        sleep_durations = [9, 9, 10, 11, 20, 20, 35, 35, 0, 0]\n        expected = [\n            1010, 1020, 1030,  # first 3 calls on schedule\n            1050, 1070,  # next 2 delayed one cycle\n            1100, 1130,  # next 2 delayed 2 cycles\n            1170, 1210,  # next 2 delayed 3 cycles\n            1220, 1230,  # then back on schedule.\n        ]\n        calls = []\n\n        def cb():\n            calls.append(self.io_loop.time())\n            if not sleep_durations:\n                self.io_loop.stop()\n                return\n            self.io_loop.sleep(sleep_durations.pop(0))\n        pc = PeriodicCallback(cb, 10000)\n        pc.start()\n        self.io_loop.start()\n        self.assertEqual(calls, expected)\n\n    def test_io_loop_set_at_start(self):\n        # Check PeriodicCallback uses the current IOLoop at start() time,\n        # not at instantiation time.\n        calls = []\n        io_loop = FakeTimeIOLoop()\n\n        def cb():\n            calls.append(io_loop.time())\n        pc = PeriodicCallback(cb, 10000)\n        io_loop.make_current()\n        pc.start()\n        io_loop.call_later(50, io_loop.stop)\n        io_loop.start()\n        self.assertEqual(calls, [1010, 1020, 1030, 1040, 1050])\n        io_loop.close()\n\n\nclass TestIOLoopConfiguration(unittest.TestCase):\n    def run_python(self, *statements):\n        statements = [\n            'from tornado.ioloop import IOLoop, PollIOLoop',\n            'classname = lambda x: x.__class__.__name__',\n        ] + list(statements)\n        args = [sys.executable, '-c', '; '.join(statements)]\n        return native_str(subprocess.check_output(args)).strip()\n\n    def test_default(self):\n        if asyncio is not None:\n            # When asyncio is available, it is used by default.\n            cls = self.run_python('print(classname(IOLoop.current()))')\n            self.assertEqual(cls, 'AsyncIOMainLoop')\n            cls = self.run_python('print(classname(IOLoop()))')\n            self.assertEqual(cls, 'AsyncIOLoop')\n        else:\n            # Otherwise, the default is a subclass of PollIOLoop\n            is_poll = self.run_python(\n                'print(isinstance(IOLoop.current(), PollIOLoop))')\n            self.assertEqual(is_poll, 'True')\n\n    @unittest.skipIf(asyncio is not None,\n                     \"IOLoop configuration not available\")\n    def test_explicit_select(self):\n        # SelectIOLoop can always be configured explicitly.\n        default_class = self.run_python(\n            'IOLoop.configure(\"tornado.platform.select.SelectIOLoop\")',\n            'print(classname(IOLoop.current()))')\n        self.assertEqual(default_class, 'SelectIOLoop')\n\n    @unittest.skipIf(asyncio is None, \"asyncio module not present\")\n    def test_asyncio(self):\n        cls = self.run_python(\n            'IOLoop.configure(\"tornado.platform.asyncio.AsyncIOLoop\")',\n            'print(classname(IOLoop.current()))')\n        self.assertEqual(cls, 'AsyncIOMainLoop')\n\n    @unittest.skipIf(asyncio is None, \"asyncio module not present\")\n    def test_asyncio_main(self):\n        cls = self.run_python(\n            'from tornado.platform.asyncio import AsyncIOMainLoop',\n            'AsyncIOMainLoop().install()',\n            'print(classname(IOLoop.current()))')\n        self.assertEqual(cls, 'AsyncIOMainLoop')\n\n    @unittest.skipIf(twisted is None, \"twisted module not present\")\n    @unittest.skipIf(asyncio is not None,\n                     \"IOLoop configuration not available\")\n    def test_twisted(self):\n        cls = self.run_python(\n            'from tornado.platform.twisted import TwistedIOLoop',\n            'TwistedIOLoop().install()',\n            'print(classname(IOLoop.current()))')\n        self.assertEqual(cls, 'TwistedIOLoop')\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
            "new_file_content": "from __future__ import absolute_import, division, print_function\n\nfrom concurrent.futures import ThreadPoolExecutor\nimport contextlib\nimport datetime\nimport functools\nimport socket\nimport subprocess\nimport sys\nimport threading\nimport time\nimport types\n\nfrom tornado.escape import native_str\nfrom tornado import gen\nfrom tornado.ioloop import IOLoop, TimeoutError, PollIOLoop, PeriodicCallback\nfrom tornado.log import app_log\nfrom tornado.platform.select import _Select\nfrom tornado.stack_context import ExceptionStackContext, StackContext, wrap, NullContext\nfrom tornado.testing import AsyncTestCase, bind_unused_port, ExpectLog, gen_test\nfrom tornado.test.util import unittest, skipIfNonUnix, skipOnTravis, skipBefore35, exec_test\n\ntry:\n    from concurrent import futures\nexcept ImportError:\n    futures = None\n\ntry:\n    import asyncio\nexcept ImportError:\n    asyncio = None\n\ntry:\n    import twisted\nexcept ImportError:\n    twisted = None\n\n\nclass FakeTimeSelect(_Select):\n    def __init__(self):\n        self._time = 1000\n        super(FakeTimeSelect, self).__init__()\n\n    def time(self):\n        return self._time\n\n    def sleep(self, t):\n        self._time += t\n\n    def poll(self, timeout):\n        events = super(FakeTimeSelect, self).poll(0)\n        if events:\n            return events\n        self._time += timeout\n        return []\n\n\nclass FakeTimeIOLoop(PollIOLoop):\n    \"\"\"IOLoop implementation with a fake and deterministic clock.\n\n    The clock advances as needed to trigger timeouts immediately.\n    For use when testing code that involves the passage of time\n    and no external dependencies.\n    \"\"\"\n    def initialize(self):\n        self.fts = FakeTimeSelect()\n        super(FakeTimeIOLoop, self).initialize(impl=self.fts,\n                                               time_func=self.fts.time)\n\n    def sleep(self, t):\n        \"\"\"Simulate a blocking sleep by advancing the clock.\"\"\"\n        self.fts.sleep(t)\n\n\nclass TestIOLoop(AsyncTestCase):\n    def test_add_callback_return_sequence(self):\n        # A callback returning {} or [] shouldn't spin the CPU, see Issue #1803.\n        self.calls = 0\n\n        loop = self.io_loop\n        test = self\n        old_add_callback = loop.add_callback\n\n        def add_callback(self, callback, *args, **kwargs):\n            test.calls += 1\n            old_add_callback(callback, *args, **kwargs)\n\n        loop.add_callback = types.MethodType(add_callback, loop)\n        loop.add_callback(lambda: {})\n        loop.add_callback(lambda: [])\n        loop.add_timeout(datetime.timedelta(milliseconds=50), loop.stop)\n        loop.start()\n        self.assertLess(self.calls, 10)\n\n    @skipOnTravis\n    def test_add_callback_wakeup(self):\n        # Make sure that add_callback from inside a running IOLoop\n        # wakes up the IOLoop immediately instead of waiting for a timeout.\n        def callback():\n            self.called = True\n            self.stop()\n\n        def schedule_callback():\n            self.called = False\n            self.io_loop.add_callback(callback)\n            # Store away the time so we can check if we woke up immediately\n            self.start_time = time.time()\n        self.io_loop.add_timeout(self.io_loop.time(), schedule_callback)\n        self.wait()\n        self.assertAlmostEqual(time.time(), self.start_time, places=2)\n        self.assertTrue(self.called)\n\n    @skipOnTravis\n    def test_add_callback_wakeup_other_thread(self):\n        def target():\n            # sleep a bit to let the ioloop go into its poll loop\n            time.sleep(0.01)\n            self.stop_time = time.time()\n            self.io_loop.add_callback(self.stop)\n        thread = threading.Thread(target=target)\n        self.io_loop.add_callback(thread.start)\n        self.wait()\n        delta = time.time() - self.stop_time\n        self.assertLess(delta, 0.1)\n        thread.join()\n\n    def test_add_timeout_timedelta(self):\n        self.io_loop.add_timeout(datetime.timedelta(microseconds=1), self.stop)\n        self.wait()\n\n    def test_multiple_add(self):\n        sock, port = bind_unused_port()\n        try:\n            self.io_loop.add_handler(sock.fileno(), lambda fd, events: None,\n                                     IOLoop.READ)\n            # Attempting to add the same handler twice fails\n            # (with a platform-dependent exception)\n            self.assertRaises(Exception, self.io_loop.add_handler,\n                              sock.fileno(), lambda fd, events: None,\n                              IOLoop.READ)\n        finally:\n            self.io_loop.remove_handler(sock.fileno())\n            sock.close()\n\n    def test_remove_without_add(self):\n        # remove_handler should not throw an exception if called on an fd\n        # was never added.\n        sock, port = bind_unused_port()\n        try:\n            self.io_loop.remove_handler(sock.fileno())\n        finally:\n            sock.close()\n\n    def test_add_callback_from_signal(self):\n        # cheat a little bit and just run this normally, since we can't\n        # easily simulate the races that happen with real signal handlers\n        self.io_loop.add_callback_from_signal(self.stop)\n        self.wait()\n\n    def test_add_callback_from_signal_other_thread(self):\n        # Very crude test, just to make sure that we cover this case.\n        # This also happens to be the first test where we run an IOLoop in\n        # a non-main thread.\n        other_ioloop = IOLoop()\n        thread = threading.Thread(target=other_ioloop.start)\n        thread.start()\n        other_ioloop.add_callback_from_signal(other_ioloop.stop)\n        thread.join()\n        other_ioloop.close()\n\n    def test_add_callback_while_closing(self):\n        # add_callback should not fail if it races with another thread\n        # closing the IOLoop. The callbacks are dropped silently\n        # without executing.\n        closing = threading.Event()\n\n        def target():\n            other_ioloop.add_callback(other_ioloop.stop)\n            other_ioloop.start()\n            closing.set()\n            other_ioloop.close(all_fds=True)\n        other_ioloop = IOLoop()\n        thread = threading.Thread(target=target)\n        thread.start()\n        closing.wait()\n        for i in range(1000):\n            other_ioloop.add_callback(lambda: None)\n\n    def test_handle_callback_exception(self):\n        # IOLoop.handle_callback_exception can be overridden to catch\n        # exceptions in callbacks.\n        def handle_callback_exception(callback):\n            self.assertIs(sys.exc_info()[0], ZeroDivisionError)\n            self.stop()\n        self.io_loop.handle_callback_exception = handle_callback_exception\n        with NullContext():\n            # remove the test StackContext that would see this uncaught\n            # exception as a test failure.\n            self.io_loop.add_callback(lambda: 1 / 0)\n        self.wait()\n\n    @skipIfNonUnix  # just because socketpair is so convenient\n    def test_read_while_writeable(self):\n        # Ensure that write events don't come in while we're waiting for\n        # a read and haven't asked for writeability. (the reverse is\n        # difficult to test for)\n        client, server = socket.socketpair()\n        try:\n            def handler(fd, events):\n                self.assertEqual(events, IOLoop.READ)\n                self.stop()\n            self.io_loop.add_handler(client.fileno(), handler, IOLoop.READ)\n            self.io_loop.add_timeout(self.io_loop.time() + 0.01,\n                                     functools.partial(server.send, b'asdf'))\n            self.wait()\n            self.io_loop.remove_handler(client.fileno())\n        finally:\n            client.close()\n            server.close()\n\n    def test_remove_timeout_after_fire(self):\n        # It is not an error to call remove_timeout after it has run.\n        handle = self.io_loop.add_timeout(self.io_loop.time(), self.stop)\n        self.wait()\n        self.io_loop.remove_timeout(handle)\n\n    def test_remove_timeout_cleanup(self):\n        # Add and remove enough callbacks to trigger cleanup.\n        # Not a very thorough test, but it ensures that the cleanup code\n        # gets executed and doesn't blow up.  This test is only really useful\n        # on PollIOLoop subclasses, but it should run silently on any\n        # implementation.\n        for i in range(2000):\n            timeout = self.io_loop.add_timeout(self.io_loop.time() + 3600,\n                                               lambda: None)\n            self.io_loop.remove_timeout(timeout)\n        # HACK: wait two IOLoop iterations for the GC to happen.\n        self.io_loop.add_callback(lambda: self.io_loop.add_callback(self.stop))\n        self.wait()\n\n    def test_remove_timeout_from_timeout(self):\n        calls = [False, False]\n\n        # Schedule several callbacks and wait for them all to come due at once.\n        # t2 should be cancelled by t1, even though it is already scheduled to\n        # be run before the ioloop even looks at it.\n        now = self.io_loop.time()\n\n        def t1():\n            calls[0] = True\n            self.io_loop.remove_timeout(t2_handle)\n        self.io_loop.add_timeout(now + 0.01, t1)\n\n        def t2():\n            calls[1] = True\n        t2_handle = self.io_loop.add_timeout(now + 0.02, t2)\n        self.io_loop.add_timeout(now + 0.03, self.stop)\n        time.sleep(0.03)\n        self.wait()\n        self.assertEqual(calls, [True, False])\n\n    def test_timeout_with_arguments(self):\n        # This tests that all the timeout methods pass through *args correctly.\n        results = []\n        self.io_loop.add_timeout(self.io_loop.time(), results.append, 1)\n        self.io_loop.add_timeout(datetime.timedelta(seconds=0),\n                                 results.append, 2)\n        self.io_loop.call_at(self.io_loop.time(), results.append, 3)\n        self.io_loop.call_later(0, results.append, 4)\n        self.io_loop.call_later(0, self.stop)\n        self.wait()\n        # The asyncio event loop does not guarantee the order of these\n        # callbacks, but PollIOLoop does.\n        self.assertEqual(sorted(results), [1, 2, 3, 4])\n\n    def test_add_timeout_return(self):\n        # All the timeout methods return non-None handles that can be\n        # passed to remove_timeout.\n        handle = self.io_loop.add_timeout(self.io_loop.time(), lambda: None)\n        self.assertFalse(handle is None)\n        self.io_loop.remove_timeout(handle)\n\n    def test_call_at_return(self):\n        handle = self.io_loop.call_at(self.io_loop.time(), lambda: None)\n        self.assertFalse(handle is None)\n        self.io_loop.remove_timeout(handle)\n\n    def test_call_later_return(self):\n        handle = self.io_loop.call_later(0, lambda: None)\n        self.assertFalse(handle is None)\n        self.io_loop.remove_timeout(handle)\n\n    def test_close_file_object(self):\n        \"\"\"When a file object is used instead of a numeric file descriptor,\n        the object should be closed (by IOLoop.close(all_fds=True),\n        not just the fd.\n        \"\"\"\n        # Use a socket since they are supported by IOLoop on all platforms.\n        # Unfortunately, sockets don't support the .closed attribute for\n        # inspecting their close status, so we must use a wrapper.\n        class SocketWrapper(object):\n            def __init__(self, sockobj):\n                self.sockobj = sockobj\n                self.closed = False\n\n            def fileno(self):\n                return self.sockobj.fileno()\n\n            def close(self):\n                self.closed = True\n                self.sockobj.close()\n        sockobj, port = bind_unused_port()\n        socket_wrapper = SocketWrapper(sockobj)\n        io_loop = IOLoop()\n        io_loop.add_handler(socket_wrapper, lambda fd, events: None,\n                            IOLoop.READ)\n        io_loop.close(all_fds=True)\n        self.assertTrue(socket_wrapper.closed)\n\n    def test_handler_callback_file_object(self):\n        \"\"\"The handler callback receives the same fd object it passed in.\"\"\"\n        server_sock, port = bind_unused_port()\n        fds = []\n\n        def handle_connection(fd, events):\n            fds.append(fd)\n            conn, addr = server_sock.accept()\n            conn.close()\n            self.stop()\n        self.io_loop.add_handler(server_sock, handle_connection, IOLoop.READ)\n        with contextlib.closing(socket.socket()) as client_sock:\n            client_sock.connect(('127.0.0.1', port))\n            self.wait()\n        self.io_loop.remove_handler(server_sock)\n        self.io_loop.add_handler(server_sock.fileno(), handle_connection,\n                                 IOLoop.READ)\n        with contextlib.closing(socket.socket()) as client_sock:\n            client_sock.connect(('127.0.0.1', port))\n            self.wait()\n        self.assertIs(fds[0], server_sock)\n        self.assertEqual(fds[1], server_sock.fileno())\n        self.io_loop.remove_handler(server_sock.fileno())\n        server_sock.close()\n\n    def test_mixed_fd_fileobj(self):\n        server_sock, port = bind_unused_port()\n\n        def f(fd, events):\n            pass\n        self.io_loop.add_handler(server_sock, f, IOLoop.READ)\n        with self.assertRaises(Exception):\n            # The exact error is unspecified - some implementations use\n            # IOError, others use ValueError.\n            self.io_loop.add_handler(server_sock.fileno(), f, IOLoop.READ)\n        self.io_loop.remove_handler(server_sock.fileno())\n        server_sock.close()\n\n    def test_reentrant(self):\n        \"\"\"Calling start() twice should raise an error, not deadlock.\"\"\"\n        returned_from_start = [False]\n        got_exception = [False]\n\n        def callback():\n            try:\n                self.io_loop.start()\n                returned_from_start[0] = True\n            except Exception:\n                got_exception[0] = True\n            self.stop()\n        self.io_loop.add_callback(callback)\n        self.wait()\n        self.assertTrue(got_exception[0])\n        self.assertFalse(returned_from_start[0])\n\n    def test_exception_logging(self):\n        \"\"\"Uncaught exceptions get logged by the IOLoop.\"\"\"\n        # Use a NullContext to keep the exception from being caught by\n        # AsyncTestCase.\n        with NullContext():\n            self.io_loop.add_callback(lambda: 1 / 0)\n            self.io_loop.add_callback(self.stop)\n            with ExpectLog(app_log, \"Exception in callback\"):\n                self.wait()\n\n    def test_exception_logging_future(self):\n        \"\"\"The IOLoop examines exceptions from Futures and logs them.\"\"\"\n        with NullContext():\n            @gen.coroutine\n            def callback():\n                self.io_loop.add_callback(self.stop)\n                1 / 0\n            self.io_loop.add_callback(callback)\n            with ExpectLog(app_log, \"Exception in callback\"):\n                self.wait()\n\n    @skipBefore35\n    def test_exception_logging_native_coro(self):\n        \"\"\"The IOLoop examines exceptions from awaitables and logs them.\"\"\"\n        namespace = exec_test(globals(), locals(), \"\"\"\n        async def callback():\n            # Stop the IOLoop two iterations after raising an exception\n            # to give the exception time to be logged.\n            self.io_loop.add_callback(self.io_loop.add_callback, self.stop)\n            1 / 0\n        \"\"\")\n        with NullContext():\n            self.io_loop.add_callback(namespace[\"callback\"])\n            with ExpectLog(app_log, \"Exception in callback\"):\n                self.wait()\n\n    def test_spawn_callback(self):\n        # An added callback runs in the test's stack_context, so will be\n        # re-raised in wait().\n        self.io_loop.add_callback(lambda: 1 / 0)\n        with self.assertRaises(ZeroDivisionError):\n            self.wait()\n        # A spawned callback is run directly on the IOLoop, so it will be\n        # logged without stopping the test.\n        self.io_loop.spawn_callback(lambda: 1 / 0)\n        self.io_loop.add_callback(self.stop)\n        with ExpectLog(app_log, \"Exception in callback\"):\n            self.wait()\n\n    @skipIfNonUnix\n    def test_remove_handler_from_handler(self):\n        # Create two sockets with simultaneous read events.\n        client, server = socket.socketpair()\n        try:\n            client.send(b'abc')\n            server.send(b'abc')\n\n            # After reading from one fd, remove the other from the IOLoop.\n            chunks = []\n\n            def handle_read(fd, events):\n                chunks.append(fd.recv(1024))\n                if fd is client:\n                    self.io_loop.remove_handler(server)\n                else:\n                    self.io_loop.remove_handler(client)\n            self.io_loop.add_handler(client, handle_read, self.io_loop.READ)\n            self.io_loop.add_handler(server, handle_read, self.io_loop.READ)\n            self.io_loop.call_later(0.1, self.stop)\n            self.wait()\n\n            # Only one fd was read; the other was cleanly removed.\n            self.assertEqual(chunks, [b'abc'])\n        finally:\n            client.close()\n            server.close()\n\n\n# Deliberately not a subclass of AsyncTestCase so the IOLoop isn't\n# automatically set as current.\nclass TestIOLoopCurrent(unittest.TestCase):\n    def setUp(self):\n        self.io_loop = None\n        IOLoop.clear_current()\n\n    def tearDown(self):\n        if self.io_loop is not None:\n            self.io_loop.close()\n\n    def test_default_current(self):\n        self.io_loop = IOLoop()\n        # The first IOLoop with default arguments is made current.\n        self.assertIs(self.io_loop, IOLoop.current())\n        # A second IOLoop can be created but is not made current.\n        io_loop2 = IOLoop()\n        self.assertIs(self.io_loop, IOLoop.current())\n        io_loop2.close()\n\n    def test_non_current(self):\n        self.io_loop = IOLoop(make_current=False)\n        # The new IOLoop is not initially made current.\n        self.assertIsNone(IOLoop.current(instance=False))\n        # Starting the IOLoop makes it current, and stopping the loop\n        # makes it non-current. This process is repeatable.\n        for i in range(3):\n            def f():\n                self.current_io_loop = IOLoop.current()\n                self.io_loop.stop()\n            self.io_loop.add_callback(f)\n            self.io_loop.start()\n            self.assertIs(self.current_io_loop, self.io_loop)\n            # Now that the loop is stopped, it is no longer current.\n            self.assertIsNone(IOLoop.current(instance=False))\n\n    def test_force_current(self):\n        self.io_loop = IOLoop(make_current=True)\n        self.assertIs(self.io_loop, IOLoop.current())\n        with self.assertRaises(RuntimeError):\n            # A second make_current=True construction cannot succeed.\n            IOLoop(make_current=True)\n        # current() was not affected by the failed construction.\n        self.assertIs(self.io_loop, IOLoop.current())\n\n\nclass TestIOLoopCurrentAsync(AsyncTestCase):\n    @gen_test\n    def test_clear_without_current(self):\n        # If there is no current IOLoop, clear_current is a no-op (but\n        # should not fail). Use a thread so we see the threading.Local\n        # in a pristine state.\n        with ThreadPoolExecutor(1) as e:\n            yield e.submit(IOLoop.clear_current)\n\n\nclass TestIOLoopAddCallback(AsyncTestCase):\n    def setUp(self):\n        super(TestIOLoopAddCallback, self).setUp()\n        self.active_contexts = []\n\n    def add_callback(self, callback, *args, **kwargs):\n        self.io_loop.add_callback(callback, *args, **kwargs)\n\n    @contextlib.contextmanager\n    def context(self, name):\n        self.active_contexts.append(name)\n        yield\n        self.assertEqual(self.active_contexts.pop(), name)\n\n    def test_pre_wrap(self):\n        # A pre-wrapped callback is run in the context in which it was\n        # wrapped, not when it was added to the IOLoop.\n        def f1():\n            self.assertIn('c1', self.active_contexts)\n            self.assertNotIn('c2', self.active_contexts)\n            self.stop()\n\n        with StackContext(functools.partial(self.context, 'c1')):\n            wrapped = wrap(f1)\n\n        with StackContext(functools.partial(self.context, 'c2')):\n            self.add_callback(wrapped)\n\n        self.wait()\n\n    def test_pre_wrap_with_args(self):\n        # Same as test_pre_wrap, but the function takes arguments.\n        # Implementation note: The function must not be wrapped in a\n        # functools.partial until after it has been passed through\n        # stack_context.wrap\n        def f1(foo, bar):\n            self.assertIn('c1', self.active_contexts)\n            self.assertNotIn('c2', self.active_contexts)\n            self.stop((foo, bar))\n\n        with StackContext(functools.partial(self.context, 'c1')):\n            wrapped = wrap(f1)\n\n        with StackContext(functools.partial(self.context, 'c2')):\n            self.add_callback(wrapped, 1, bar=2)\n\n        result = self.wait()\n        self.assertEqual(result, (1, 2))\n\n\nclass TestIOLoopAddCallbackFromSignal(TestIOLoopAddCallback):\n    # Repeat the add_callback tests using add_callback_from_signal\n    def add_callback(self, callback, *args, **kwargs):\n        self.io_loop.add_callback_from_signal(callback, *args, **kwargs)\n\n\n@unittest.skipIf(futures is None, \"futures module not present\")\nclass TestIOLoopFutures(AsyncTestCase):\n    def test_add_future_threads(self):\n        with futures.ThreadPoolExecutor(1) as pool:\n            self.io_loop.add_future(pool.submit(lambda: None),\n                                    lambda future: self.stop(future))\n            future = self.wait()\n            self.assertTrue(future.done())\n            self.assertTrue(future.result() is None)\n\n    def test_add_future_stack_context(self):\n        ready = threading.Event()\n\n        def task():\n            # we must wait for the ioloop callback to be scheduled before\n            # the task completes to ensure that add_future adds the callback\n            # asynchronously (which is the scenario in which capturing\n            # the stack_context matters)\n            ready.wait(1)\n            assert ready.isSet(), \"timed out\"\n            raise Exception(\"worker\")\n\n        def callback(future):\n            self.future = future\n            raise Exception(\"callback\")\n\n        def handle_exception(typ, value, traceback):\n            self.exception = value\n            self.stop()\n            return True\n\n        # stack_context propagates to the ioloop callback, but the worker\n        # task just has its exceptions caught and saved in the Future.\n        with futures.ThreadPoolExecutor(1) as pool:\n            with ExceptionStackContext(handle_exception):\n                self.io_loop.add_future(pool.submit(task), callback)\n            ready.set()\n        self.wait()\n\n        self.assertEqual(self.exception.args[0], \"callback\")\n        self.assertEqual(self.future.exception().args[0], \"worker\")\n\n    @gen_test\n    def test_run_in_executor_gen(self):\n        event1 = threading.Event()\n        event2 = threading.Event()\n\n        def sync_func(self_event, other_event):\n            self_event.set()\n            other_event.wait()\n            # Note that return value doesn't actually do anything,\n            # it is just passed through to our final assertion to\n            # make sure it is passed through properly.\n            return self_event\n\n        # Run two synchronous functions, which would deadlock if not\n        # run in parallel.\n        res = yield [\n            IOLoop.current().run_in_executor(None, sync_func, event1, event2),\n            IOLoop.current().run_in_executor(None, sync_func, event2, event1)\n        ]\n\n        self.assertEqual([event1, event2], res)\n\n    @skipBefore35\n    @gen_test\n    def test_run_in_executor_native(self):\n        event1 = threading.Event()\n        event2 = threading.Event()\n\n        def sync_func(self_event, other_event):\n            self_event.set()\n            other_event.wait()\n            return self_event\n\n        # Go through an async wrapper to ensure that the result of\n        # run_in_executor works with await and not just gen.coroutine\n        # (simply passing the underlying concurrrent future would do that).\n        namespace = exec_test(globals(), locals(), \"\"\"\n            async def async_wrapper(self_event, other_event):\n                return await IOLoop.current().run_in_executor(\n                    None, sync_func, self_event, other_event)\n        \"\"\")\n\n        res = yield [\n            namespace[\"async_wrapper\"](event1, event2),\n            namespace[\"async_wrapper\"](event2, event1)\n        ]\n\n        self.assertEqual([event1, event2], res)\n\n    @gen_test\n    def test_set_default_executor(self):\n        count = [0]\n\n        class MyExecutor(futures.ThreadPoolExecutor):\n            def submit(self, func, *args):\n                count[0] += 1\n                return super(MyExecutor, self).submit(func, *args)\n\n        event = threading.Event()\n\n        def sync_func():\n            event.set()\n\n        executor = MyExecutor(1)\n        loop = IOLoop.current()\n        loop.set_default_executor(executor)\n        yield loop.run_in_executor(None, sync_func)\n        self.assertEqual(1, count[0])\n        self.assertTrue(event.is_set())\n\n\nclass TestIOLoopRunSync(unittest.TestCase):\n    def setUp(self):\n        self.io_loop = IOLoop()\n\n    def tearDown(self):\n        self.io_loop.close()\n\n    def test_sync_result(self):\n        with self.assertRaises(gen.BadYieldError):\n            self.io_loop.run_sync(lambda: 42)\n\n    def test_sync_exception(self):\n        with self.assertRaises(ZeroDivisionError):\n            self.io_loop.run_sync(lambda: 1 / 0)\n\n    def test_async_result(self):\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            raise gen.Return(42)\n        self.assertEqual(self.io_loop.run_sync(f), 42)\n\n    def test_async_exception(self):\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            1 / 0\n        with self.assertRaises(ZeroDivisionError):\n            self.io_loop.run_sync(f)\n\n    def test_current(self):\n        def f():\n            self.assertIs(IOLoop.current(), self.io_loop)\n        self.io_loop.run_sync(f)\n\n    def test_timeout(self):\n        @gen.coroutine\n        def f():\n            yield gen.sleep(1)\n        self.assertRaises(TimeoutError, self.io_loop.run_sync, f, timeout=0.01)\n\n    @skipBefore35\n    def test_native_coroutine(self):\n        @gen.coroutine\n        def f1():\n            yield gen.moment\n\n        namespace = exec_test(globals(), locals(), \"\"\"\n        async def f2():\n            await f1()\n        \"\"\")\n        self.io_loop.run_sync(namespace['f2'])\n\n\n@unittest.skipIf(asyncio is not None,\n                 'IOLoop configuration not available')\nclass TestPeriodicCallback(unittest.TestCase):\n    def setUp(self):\n        self.io_loop = FakeTimeIOLoop()\n        self.io_loop.make_current()\n\n    def tearDown(self):\n        self.io_loop.close()\n\n    def test_basic(self):\n        calls = []\n\n        def cb():\n            calls.append(self.io_loop.time())\n        pc = PeriodicCallback(cb, 10000)\n        pc.start()\n        self.io_loop.call_later(50, self.io_loop.stop)\n        self.io_loop.start()\n        self.assertEqual(calls, [1010, 1020, 1030, 1040, 1050])\n\n    def test_overrun(self):\n        sleep_durations = [9, 9, 10, 11, 20, 20, 35, 35, 0, 0]\n        expected = [\n            1010, 1020, 1030,  # first 3 calls on schedule\n            1050, 1070,  # next 2 delayed one cycle\n            1100, 1130,  # next 2 delayed 2 cycles\n            1170, 1210,  # next 2 delayed 3 cycles\n            1220, 1230,  # then back on schedule.\n        ]\n        calls = []\n\n        def cb():\n            calls.append(self.io_loop.time())\n            if not sleep_durations:\n                self.io_loop.stop()\n                return\n            self.io_loop.sleep(sleep_durations.pop(0))\n        pc = PeriodicCallback(cb, 10000)\n        pc.start()\n        self.io_loop.start()\n        self.assertEqual(calls, expected)\n\n    def test_io_loop_set_at_start(self):\n        # Check PeriodicCallback uses the current IOLoop at start() time,\n        # not at instantiation time.\n        calls = []\n        io_loop = FakeTimeIOLoop()\n\n        def cb():\n            calls.append(io_loop.time())\n        pc = PeriodicCallback(cb, 10000)\n        io_loop.make_current()\n        pc.start()\n        io_loop.call_later(50, io_loop.stop)\n        io_loop.start()\n        self.assertEqual(calls, [1010, 1020, 1030, 1040, 1050])\n        io_loop.close()\n\n\nclass TestPeriodicCallbackMath(unittest.TestCase):\n    def simulate_calls(self, pc, durations):\n        \"\"\"Simulate a series of calls to the PeriodicCallback.\n\n        Pass a list of call durations in seconds. This method\n        returns the times at which each call would be made.\n        \"\"\"\n        calls = []\n        now = 1000\n        pc._next_timeout = now\n        for d in durations:\n            pc._update_next(now)\n            calls.append(pc._next_timeout)\n            now = pc._next_timeout + d\n        return calls\n\n    def test_basic(self):\n        pc = PeriodicCallback(None, 10000)\n        self.assertEqual(self.simulate_calls(pc, [0] * 5),\n                         [1010, 1020, 1030, 1040, 1050])\n\n    def test_overrun(self):\n        # If a call runs for too long, we skip entire cycles to get\n        # back on schedule.\n        call_durations = [9, 9, 10, 11, 20, 20, 35, 35, 0, 0, 0]\n        expected = [\n            1010, 1020, 1030,  # first 3 calls on schedule\n            1050, 1070,  # next 2 delayed one cycle\n            1100, 1130,  # next 2 delayed 2 cycles\n            1170, 1210,  # next 2 delayed 3 cycles\n            1220, 1230,  # then back on schedule.\n        ]\n\n        pc = PeriodicCallback(None, 10000)\n        self.assertEqual(self.simulate_calls(pc, call_durations),\n                         expected)\n\n\nclass TestIOLoopConfiguration(unittest.TestCase):\n    def run_python(self, *statements):\n        statements = [\n            'from tornado.ioloop import IOLoop, PollIOLoop',\n            'classname = lambda x: x.__class__.__name__',\n        ] + list(statements)\n        args = [sys.executable, '-c', '; '.join(statements)]\n        return native_str(subprocess.check_output(args)).strip()\n\n    def test_default(self):\n        if asyncio is not None:\n            # When asyncio is available, it is used by default.\n            cls = self.run_python('print(classname(IOLoop.current()))')\n            self.assertEqual(cls, 'AsyncIOMainLoop')\n            cls = self.run_python('print(classname(IOLoop()))')\n            self.assertEqual(cls, 'AsyncIOLoop')\n        else:\n            # Otherwise, the default is a subclass of PollIOLoop\n            is_poll = self.run_python(\n                'print(isinstance(IOLoop.current(), PollIOLoop))')\n            self.assertEqual(is_poll, 'True')\n\n    @unittest.skipIf(asyncio is not None,\n                     \"IOLoop configuration not available\")\n    def test_explicit_select(self):\n        # SelectIOLoop can always be configured explicitly.\n        default_class = self.run_python(\n            'IOLoop.configure(\"tornado.platform.select.SelectIOLoop\")',\n            'print(classname(IOLoop.current()))')\n        self.assertEqual(default_class, 'SelectIOLoop')\n\n    @unittest.skipIf(asyncio is None, \"asyncio module not present\")\n    def test_asyncio(self):\n        cls = self.run_python(\n            'IOLoop.configure(\"tornado.platform.asyncio.AsyncIOLoop\")',\n            'print(classname(IOLoop.current()))')\n        self.assertEqual(cls, 'AsyncIOMainLoop')\n\n    @unittest.skipIf(asyncio is None, \"asyncio module not present\")\n    def test_asyncio_main(self):\n        cls = self.run_python(\n            'from tornado.platform.asyncio import AsyncIOMainLoop',\n            'AsyncIOMainLoop().install()',\n            'print(classname(IOLoop.current()))')\n        self.assertEqual(cls, 'AsyncIOMainLoop')\n\n    @unittest.skipIf(twisted is None, \"twisted module not present\")\n    @unittest.skipIf(asyncio is not None,\n                     \"IOLoop configuration not available\")\n    def test_twisted(self):\n        cls = self.run_python(\n            'from tornado.platform.twisted import TwistedIOLoop',\n            'TwistedIOLoop().install()',\n            'print(classname(IOLoop.current()))')\n        self.assertEqual(cls, 'TwistedIOLoop')\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
            "header": {
                "file": {
                    "path": "tornado/test/ioloop_test.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "09f71c5d",
                "new_commit_hash": "a165ce71",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/test/ioloop_test.py"
            },
            "plus_file": {
                "path": "b/tornado/test/ioloop_test.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 789,
                            "length": 6
                        },
                        "new_range": {
                            "start": 789,
                            "length": 44
                        },
                        "section": "class TestPeriodicCallback(unittest.TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        io_loop.close()",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "class TestPeriodicCallbackMath(unittest.TestCase):",
                                "type": "added"
                            },
                            {
                                "content": "    def simulate_calls(self, pc, durations):",
                                "type": "added"
                            },
                            {
                                "content": "        \"\"\"Simulate a series of calls to the PeriodicCallback.",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        Pass a list of call durations in seconds. This method",
                                "type": "added"
                            },
                            {
                                "content": "        returns the times at which each call would be made.",
                                "type": "added"
                            },
                            {
                                "content": "        \"\"\"",
                                "type": "added"
                            },
                            {
                                "content": "        calls = []",
                                "type": "added"
                            },
                            {
                                "content": "        now = 1000",
                                "type": "added"
                            },
                            {
                                "content": "        pc._next_timeout = now",
                                "type": "added"
                            },
                            {
                                "content": "        for d in durations:",
                                "type": "added"
                            },
                            {
                                "content": "            pc._update_next(now)",
                                "type": "added"
                            },
                            {
                                "content": "            calls.append(pc._next_timeout)",
                                "type": "added"
                            },
                            {
                                "content": "            now = pc._next_timeout + d",
                                "type": "added"
                            },
                            {
                                "content": "        return calls",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_basic(self):",
                                "type": "added"
                            },
                            {
                                "content": "        pc = PeriodicCallback(None, 10000)",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(self.simulate_calls(pc, [0] * 5),",
                                "type": "added"
                            },
                            {
                                "content": "                         [1010, 1020, 1030, 1040, 1050])",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_overrun(self):",
                                "type": "added"
                            },
                            {
                                "content": "        # If a call runs for too long, we skip entire cycles to get",
                                "type": "added"
                            },
                            {
                                "content": "        # back on schedule.",
                                "type": "added"
                            },
                            {
                                "content": "        call_durations = [9, 9, 10, 11, 20, 20, 35, 35, 0, 0, 0]",
                                "type": "added"
                            },
                            {
                                "content": "        expected = [",
                                "type": "added"
                            },
                            {
                                "content": "            1010, 1020, 1030,  # first 3 calls on schedule",
                                "type": "added"
                            },
                            {
                                "content": "            1050, 1070,  # next 2 delayed one cycle",
                                "type": "added"
                            },
                            {
                                "content": "            1100, 1130,  # next 2 delayed 2 cycles",
                                "type": "added"
                            },
                            {
                                "content": "            1170, 1210,  # next 2 delayed 3 cycles",
                                "type": "added"
                            },
                            {
                                "content": "            1220, 1230,  # then back on schedule.",
                                "type": "added"
                            },
                            {
                                "content": "        ]",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        pc = PeriodicCallback(None, 10000)",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(self.simulate_calls(pc, call_durations),",
                                "type": "added"
                            },
                            {
                                "content": "                         expected)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "class TestIOLoopConfiguration(unittest.TestCase):",
                                "type": "context"
                            },
                            {
                                "content": "    def run_python(self, *statements):",
                                "type": "context"
                            },
                            {
                                "content": "        statements = [",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/ioloop_test.py",
                            "type": "method",
                            "name": "TestPeriodicCallbackMath.test_basic",
                            "content": "class TestPeriodicCallbackMath(unittest.TestCase):\n    def simulate_calls(self, pc, durations):\n        \"\"\"Simulate a series of calls to the PeriodicCallback.\n\n        Pass a list of call durations in seconds. This method\n        returns the times at which each call would be made.\n        \"\"\"\n        calls = []\n        now = 1000\n        pc._next_timeout = now\n        for d in durations:\n            pc._update_next(now)\n            calls.append(pc._next_timeout)\n            now = pc._next_timeout + d\n        return calls\n\n    def test_basic(self):\n        pc = PeriodicCallback(None, 10000)\n        self.assertEqual(self.simulate_calls(pc, [0] * 5),\n                         [1010, 1020, 1030, 1040, 1050])\n\n    def test_overrun(self):\n        # If a call runs for too long, we skip entire cycles to get\n        # back on schedule.\n        call_durations = [9, 9, 10, 11, 20, 20, 35, 35, 0, 0, 0]\n        expected = [\n            1010, 1020, 1030,  # first 3 calls on schedule\n            1050, 1070,  # next 2 delayed one cycle\n            1100, 1130,  # next 2 delayed 2 cycles\n            1170, 1210,  # next 2 delayed 3 cycles\n            1220, 1230,  # then back on schedule.\n        ]\n\n        pc = PeriodicCallback(None, 10000)\n        self.assertEqual(self.simulate_calls(pc, call_durations),\n                         expected)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 808,
                            "end_lineno": 811,
                            "parent": {
                                "file_name": "tornado/test/ioloop_test.py",
                                "type": "class",
                                "name": "TestPeriodicCallbackMath",
                                "content": "class TestPeriodicCallbackMath(unittest.TestCase):\n    def simulate_calls(self, pc, durations):\n        \"\"\"Simulate a series of calls to the PeriodicCallback.\n\n        Pass a list of call durations in seconds. This method\n        returns the times at which each call would be made.\n        \"\"\"\n        calls = []\n        now = 1000\n        pc._next_timeout = now\n        for d in durations:\n            pc._update_next(now)\n            calls.append(pc._next_timeout)\n            now = pc._next_timeout + d\n        return calls\n\n    def test_basic(self):\n        pc = PeriodicCallback(None, 10000)\n        self.assertEqual(self.simulate_calls(pc, [0] * 5),\n                         [1010, 1020, 1030, 1040, 1050])\n\n    def test_overrun(self):\n        # If a call runs for too long, we skip entire cycles to get\n        # back on schedule.\n        call_durations = [9, 9, 10, 11, 20, 20, 35, 35, 0, 0, 0]\n        expected = [\n            1010, 1020, 1030,  # first 3 calls on schedule\n            1050, 1070,  # next 2 delayed one cycle\n            1100, 1130,  # next 2 delayed 2 cycles\n            1170, 1210,  # next 2 delayed 3 cycles\n            1220, 1230,  # then back on schedule.\n        ]\n\n        pc = PeriodicCallback(None, 10000)\n        self.assertEqual(self.simulate_calls(pc, call_durations),\n                         expected)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 792,
                                "end_lineno": 827,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/ioloop_test.py",
                            "type": "class",
                            "name": "TestPeriodicCallbackMath",
                            "content": "class TestPeriodicCallbackMath(unittest.TestCase):\n    def simulate_calls(self, pc, durations):\n        \"\"\"Simulate a series of calls to the PeriodicCallback.\n\n        Pass a list of call durations in seconds. This method\n        returns the times at which each call would be made.\n        \"\"\"\n        calls = []\n        now = 1000\n        pc._next_timeout = now\n        for d in durations:\n            pc._update_next(now)\n            calls.append(pc._next_timeout)\n            now = pc._next_timeout + d\n        return calls\n\n    def test_basic(self):\n        pc = PeriodicCallback(None, 10000)\n        self.assertEqual(self.simulate_calls(pc, [0] * 5),\n                         [1010, 1020, 1030, 1040, 1050])\n\n    def test_overrun(self):\n        # If a call runs for too long, we skip entire cycles to get\n        # back on schedule.\n        call_durations = [9, 9, 10, 11, 20, 20, 35, 35, 0, 0, 0]\n        expected = [\n            1010, 1020, 1030,  # first 3 calls on schedule\n            1050, 1070,  # next 2 delayed one cycle\n            1100, 1130,  # next 2 delayed 2 cycles\n            1170, 1210,  # next 2 delayed 3 cycles\n            1220, 1230,  # then back on schedule.\n        ]\n\n        pc = PeriodicCallback(None, 10000)\n        self.assertEqual(self.simulate_calls(pc, call_durations),\n                         expected)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 792,
                            "end_lineno": 827,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/test/ioloop_test.py",
                            "type": "method",
                            "name": "TestPeriodicCallbackMath.test_overrun",
                            "content": "class TestPeriodicCallbackMath(unittest.TestCase):\n    def simulate_calls(self, pc, durations):\n        \"\"\"Simulate a series of calls to the PeriodicCallback.\n\n        Pass a list of call durations in seconds. This method\n        returns the times at which each call would be made.\n        \"\"\"\n        calls = []\n        now = 1000\n        pc._next_timeout = now\n        for d in durations:\n            pc._update_next(now)\n            calls.append(pc._next_timeout)\n            now = pc._next_timeout + d\n        return calls\n\n    def test_basic(self):\n        pc = PeriodicCallback(None, 10000)\n        self.assertEqual(self.simulate_calls(pc, [0] * 5),\n                         [1010, 1020, 1030, 1040, 1050])\n\n    def test_overrun(self):\n        # If a call runs for too long, we skip entire cycles to get\n        # back on schedule.\n        call_durations = [9, 9, 10, 11, 20, 20, 35, 35, 0, 0, 0]\n        expected = [\n            1010, 1020, 1030,  # first 3 calls on schedule\n            1050, 1070,  # next 2 delayed one cycle\n            1100, 1130,  # next 2 delayed 2 cycles\n            1170, 1210,  # next 2 delayed 3 cycles\n            1220, 1230,  # then back on schedule.\n        ]\n\n        pc = PeriodicCallback(None, 10000)\n        self.assertEqual(self.simulate_calls(pc, call_durations),\n                         expected)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 813,
                            "end_lineno": 827,
                            "parent": {
                                "file_name": "tornado/test/ioloop_test.py",
                                "type": "class",
                                "name": "TestPeriodicCallbackMath",
                                "content": "class TestPeriodicCallbackMath(unittest.TestCase):\n    def simulate_calls(self, pc, durations):\n        \"\"\"Simulate a series of calls to the PeriodicCallback.\n\n        Pass a list of call durations in seconds. This method\n        returns the times at which each call would be made.\n        \"\"\"\n        calls = []\n        now = 1000\n        pc._next_timeout = now\n        for d in durations:\n            pc._update_next(now)\n            calls.append(pc._next_timeout)\n            now = pc._next_timeout + d\n        return calls\n\n    def test_basic(self):\n        pc = PeriodicCallback(None, 10000)\n        self.assertEqual(self.simulate_calls(pc, [0] * 5),\n                         [1010, 1020, 1030, 1040, 1050])\n\n    def test_overrun(self):\n        # If a call runs for too long, we skip entire cycles to get\n        # back on schedule.\n        call_durations = [9, 9, 10, 11, 20, 20, 35, 35, 0, 0, 0]\n        expected = [\n            1010, 1020, 1030,  # first 3 calls on schedule\n            1050, 1070,  # next 2 delayed one cycle\n            1100, 1130,  # next 2 delayed 2 cycles\n            1170, 1210,  # next 2 delayed 3 cycles\n            1220, 1230,  # then back on schedule.\n        ]\n\n        pc = PeriodicCallback(None, 10000)\n        self.assertEqual(self.simulate_calls(pc, call_durations),\n                         expected)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 792,
                                "end_lineno": 827,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/ioloop_test.py",
                            "type": "method",
                            "name": "TestPeriodicCallbackMath.simulate_calls",
                            "content": "class TestPeriodicCallbackMath(unittest.TestCase):\n    def simulate_calls(self, pc, durations):\n        \"\"\"Simulate a series of calls to the PeriodicCallback.\n\n        Pass a list of call durations in seconds. This method\n        returns the times at which each call would be made.\n        \"\"\"\n        calls = []\n        now = 1000\n        pc._next_timeout = now\n        for d in durations:\n            pc._update_next(now)\n            calls.append(pc._next_timeout)\n            now = pc._next_timeout + d\n        return calls\n\n    def test_basic(self):\n        pc = PeriodicCallback(None, 10000)\n        self.assertEqual(self.simulate_calls(pc, [0] * 5),\n                         [1010, 1020, 1030, 1040, 1050])\n\n    def test_overrun(self):\n        # If a call runs for too long, we skip entire cycles to get\n        # back on schedule.\n        call_durations = [9, 9, 10, 11, 20, 20, 35, 35, 0, 0, 0]\n        expected = [\n            1010, 1020, 1030,  # first 3 calls on schedule\n            1050, 1070,  # next 2 delayed one cycle\n            1100, 1130,  # next 2 delayed 2 cycles\n            1170, 1210,  # next 2 delayed 3 cycles\n            1220, 1230,  # then back on schedule.\n        ]\n\n        pc = PeriodicCallback(None, 10000)\n        self.assertEqual(self.simulate_calls(pc, call_durations),\n                         expected)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 793,
                            "end_lineno": 806,
                            "parent": {
                                "file_name": "tornado/test/ioloop_test.py",
                                "type": "class",
                                "name": "TestPeriodicCallbackMath",
                                "content": "class TestPeriodicCallbackMath(unittest.TestCase):\n    def simulate_calls(self, pc, durations):\n        \"\"\"Simulate a series of calls to the PeriodicCallback.\n\n        Pass a list of call durations in seconds. This method\n        returns the times at which each call would be made.\n        \"\"\"\n        calls = []\n        now = 1000\n        pc._next_timeout = now\n        for d in durations:\n            pc._update_next(now)\n            calls.append(pc._next_timeout)\n            now = pc._next_timeout + d\n        return calls\n\n    def test_basic(self):\n        pc = PeriodicCallback(None, 10000)\n        self.assertEqual(self.simulate_calls(pc, [0] * 5),\n                         [1010, 1020, 1030, 1040, 1050])\n\n    def test_overrun(self):\n        # If a call runs for too long, we skip entire cycles to get\n        # back on schedule.\n        call_durations = [9, 9, 10, 11, 20, 20, 35, 35, 0, 0, 0]\n        expected = [\n            1010, 1020, 1030,  # first 3 calls on schedule\n            1050, 1070,  # next 2 delayed one cycle\n            1100, 1130,  # next 2 delayed 2 cycles\n            1170, 1210,  # next 2 delayed 3 cycles\n            1220, 1230,  # then back on schedule.\n        ]\n\n        pc = PeriodicCallback(None, 10000)\n        self.assertEqual(self.simulate_calls(pc, call_durations),\n                         expected)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 792,
                                "end_lineno": 827,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "2d4053daa56c609d642b214399e046671d4a593e^",
    "new_commit_hash": "2d4053daa56c609d642b214399e046671d4a593e",
    "commit_message": "ioloop: Factor out the math of PeriodicCallback for easier testing\n\nThis permits it to be tested separately from the (now python 2.7-only)\nIOLoop configuration.",
    "commit_date": "2018-03-31T17:34:40-04:00",
    "metadata": {}
}
{
    "repo_name": "tornado",
    "new_commit_hash": "2d4053daa56c609d642b214399e046671d4a593e",
    "test_file_codes": [
        "from __future__ import absolute_import, division, print_function\n\nfrom concurrent.futures import ThreadPoolExecutor\nimport contextlib\nimport datetime\nimport functools\nimport socket\nimport subprocess\nimport sys\nimport threading\nimport time\nimport types\n\nfrom tornado.escape import native_str\nfrom tornado import gen\nfrom tornado.ioloop import IOLoop, TimeoutError, PollIOLoop, PeriodicCallback\nfrom tornado.log import app_log\nfrom tornado.platform.select import _Select\nfrom tornado.stack_context import ExceptionStackContext, StackContext, wrap, NullContext\nfrom tornado.testing import AsyncTestCase, bind_unused_port, ExpectLog, gen_test\nfrom tornado.test.util import unittest, skipIfNonUnix, skipOnTravis, skipBefore35, exec_test\n\ntry:\n    from concurrent import futures\nexcept ImportError:\n    futures = None\n\ntry:\n    import asyncio\nexcept ImportError:\n    asyncio = None\n\ntry:\n    import twisted\nexcept ImportError:\n    twisted = None\n\n\nclass FakeTimeSelect(_Select):\n    def __init__(self):\n        self._time = 1000\n        super(FakeTimeSelect, self).__init__()\n\n    def time(self):\n        return self._time\n\n    def sleep(self, t):\n        self._time += t\n\n    def poll(self, timeout):\n        events = super(FakeTimeSelect, self).poll(0)\n        if events:\n            return events\n        self._time += timeout\n        return []\n\n\nclass FakeTimeIOLoop(PollIOLoop):\n    \"\"\"IOLoop implementation with a fake and deterministic clock.\n\n    The clock advances as needed to trigger timeouts immediately.\n    For use when testing code that involves the passage of time\n    and no external dependencies.\n    \"\"\"\n    def initialize(self):\n        self.fts = FakeTimeSelect()\n        super(FakeTimeIOLoop, self).initialize(impl=self.fts,\n                                               time_func=self.fts.time)\n\n    def sleep(self, t):\n        \"\"\"Simulate a blocking sleep by advancing the clock.\"\"\"\n        self.fts.sleep(t)\n\n\nclass TestIOLoop(AsyncTestCase):\n    def test_add_callback_return_sequence(self):\n        # A callback returning {} or [] shouldn't spin the CPU, see Issue #1803.\n        self.calls = 0\n\n        loop = self.io_loop\n        test = self\n        old_add_callback = loop.add_callback\n\n        def add_callback(self, callback, *args, **kwargs):\n            test.calls += 1\n            old_add_callback(callback, *args, **kwargs)\n\n        loop.add_callback = types.MethodType(add_callback, loop)\n        loop.add_callback(lambda: {})\n        loop.add_callback(lambda: [])\n        loop.add_timeout(datetime.timedelta(milliseconds=50), loop.stop)\n        loop.start()\n        self.assertLess(self.calls, 10)\n\n    @skipOnTravis\n    def test_add_callback_wakeup(self):\n        # Make sure that add_callback from inside a running IOLoop\n        # wakes up the IOLoop immediately instead of waiting for a timeout.\n        def callback():\n            self.called = True\n            self.stop()\n\n        def schedule_callback():\n            self.called = False\n            self.io_loop.add_callback(callback)\n            # Store away the time so we can check if we woke up immediately\n            self.start_time = time.time()\n        self.io_loop.add_timeout(self.io_loop.time(), schedule_callback)\n        self.wait()\n        self.assertAlmostEqual(time.time(), self.start_time, places=2)\n        self.assertTrue(self.called)\n\n    @skipOnTravis\n    def test_add_callback_wakeup_other_thread(self):\n        def target():\n            # sleep a bit to let the ioloop go into its poll loop\n            time.sleep(0.01)\n            self.stop_time = time.time()\n            self.io_loop.add_callback(self.stop)\n        thread = threading.Thread(target=target)\n        self.io_loop.add_callback(thread.start)\n        self.wait()\n        delta = time.time() - self.stop_time\n        self.assertLess(delta, 0.1)\n        thread.join()\n\n    def test_add_timeout_timedelta(self):\n        self.io_loop.add_timeout(datetime.timedelta(microseconds=1), self.stop)\n        self.wait()\n\n    def test_multiple_add(self):\n        sock, port = bind_unused_port()\n        try:\n            self.io_loop.add_handler(sock.fileno(), lambda fd, events: None,\n                                     IOLoop.READ)\n            # Attempting to add the same handler twice fails\n            # (with a platform-dependent exception)\n            self.assertRaises(Exception, self.io_loop.add_handler,\n                              sock.fileno(), lambda fd, events: None,\n                              IOLoop.READ)\n        finally:\n            self.io_loop.remove_handler(sock.fileno())\n            sock.close()\n\n    def test_remove_without_add(self):\n        # remove_handler should not throw an exception if called on an fd\n        # was never added.\n        sock, port = bind_unused_port()\n        try:\n            self.io_loop.remove_handler(sock.fileno())\n        finally:\n            sock.close()\n\n    def test_add_callback_from_signal(self):\n        # cheat a little bit and just run this normally, since we can't\n        # easily simulate the races that happen with real signal handlers\n        self.io_loop.add_callback_from_signal(self.stop)\n        self.wait()\n\n    def test_add_callback_from_signal_other_thread(self):\n        # Very crude test, just to make sure that we cover this case.\n        # This also happens to be the first test where we run an IOLoop in\n        # a non-main thread.\n        other_ioloop = IOLoop()\n        thread = threading.Thread(target=other_ioloop.start)\n        thread.start()\n        other_ioloop.add_callback_from_signal(other_ioloop.stop)\n        thread.join()\n        other_ioloop.close()\n\n    def test_add_callback_while_closing(self):\n        # add_callback should not fail if it races with another thread\n        # closing the IOLoop. The callbacks are dropped silently\n        # without executing.\n        closing = threading.Event()\n\n        def target():\n            other_ioloop.add_callback(other_ioloop.stop)\n            other_ioloop.start()\n            closing.set()\n            other_ioloop.close(all_fds=True)\n        other_ioloop = IOLoop()\n        thread = threading.Thread(target=target)\n        thread.start()\n        closing.wait()\n        for i in range(1000):\n            other_ioloop.add_callback(lambda: None)\n\n    def test_handle_callback_exception(self):\n        # IOLoop.handle_callback_exception can be overridden to catch\n        # exceptions in callbacks.\n        def handle_callback_exception(callback):\n            self.assertIs(sys.exc_info()[0], ZeroDivisionError)\n            self.stop()\n        self.io_loop.handle_callback_exception = handle_callback_exception\n        with NullContext():\n            # remove the test StackContext that would see this uncaught\n            # exception as a test failure.\n            self.io_loop.add_callback(lambda: 1 / 0)\n        self.wait()\n\n    @skipIfNonUnix  # just because socketpair is so convenient\n    def test_read_while_writeable(self):\n        # Ensure that write events don't come in while we're waiting for\n        # a read and haven't asked for writeability. (the reverse is\n        # difficult to test for)\n        client, server = socket.socketpair()\n        try:\n            def handler(fd, events):\n                self.assertEqual(events, IOLoop.READ)\n                self.stop()\n            self.io_loop.add_handler(client.fileno(), handler, IOLoop.READ)\n            self.io_loop.add_timeout(self.io_loop.time() + 0.01,\n                                     functools.partial(server.send, b'asdf'))\n            self.wait()\n            self.io_loop.remove_handler(client.fileno())\n        finally:\n            client.close()\n            server.close()\n\n    def test_remove_timeout_after_fire(self):\n        # It is not an error to call remove_timeout after it has run.\n        handle = self.io_loop.add_timeout(self.io_loop.time(), self.stop)\n        self.wait()\n        self.io_loop.remove_timeout(handle)\n\n    def test_remove_timeout_cleanup(self):\n        # Add and remove enough callbacks to trigger cleanup.\n        # Not a very thorough test, but it ensures that the cleanup code\n        # gets executed and doesn't blow up.  This test is only really useful\n        # on PollIOLoop subclasses, but it should run silently on any\n        # implementation.\n        for i in range(2000):\n            timeout = self.io_loop.add_timeout(self.io_loop.time() + 3600,\n                                               lambda: None)\n            self.io_loop.remove_timeout(timeout)\n        # HACK: wait two IOLoop iterations for the GC to happen.\n        self.io_loop.add_callback(lambda: self.io_loop.add_callback(self.stop))\n        self.wait()\n\n    def test_remove_timeout_from_timeout(self):\n        calls = [False, False]\n\n        # Schedule several callbacks and wait for them all to come due at once.\n        # t2 should be cancelled by t1, even though it is already scheduled to\n        # be run before the ioloop even looks at it.\n        now = self.io_loop.time()\n\n        def t1():\n            calls[0] = True\n            self.io_loop.remove_timeout(t2_handle)\n        self.io_loop.add_timeout(now + 0.01, t1)\n\n        def t2():\n            calls[1] = True\n        t2_handle = self.io_loop.add_timeout(now + 0.02, t2)\n        self.io_loop.add_timeout(now + 0.03, self.stop)\n        time.sleep(0.03)\n        self.wait()\n        self.assertEqual(calls, [True, False])\n\n    def test_timeout_with_arguments(self):\n        # This tests that all the timeout methods pass through *args correctly.\n        results = []\n        self.io_loop.add_timeout(self.io_loop.time(), results.append, 1)\n        self.io_loop.add_timeout(datetime.timedelta(seconds=0),\n                                 results.append, 2)\n        self.io_loop.call_at(self.io_loop.time(), results.append, 3)\n        self.io_loop.call_later(0, results.append, 4)\n        self.io_loop.call_later(0, self.stop)\n        self.wait()\n        # The asyncio event loop does not guarantee the order of these\n        # callbacks, but PollIOLoop does.\n        self.assertEqual(sorted(results), [1, 2, 3, 4])\n\n    def test_add_timeout_return(self):\n        # All the timeout methods return non-None handles that can be\n        # passed to remove_timeout.\n        handle = self.io_loop.add_timeout(self.io_loop.time(), lambda: None)\n        self.assertFalse(handle is None)\n        self.io_loop.remove_timeout(handle)\n\n    def test_call_at_return(self):\n        handle = self.io_loop.call_at(self.io_loop.time(), lambda: None)\n        self.assertFalse(handle is None)\n        self.io_loop.remove_timeout(handle)\n\n    def test_call_later_return(self):\n        handle = self.io_loop.call_later(0, lambda: None)\n        self.assertFalse(handle is None)\n        self.io_loop.remove_timeout(handle)\n\n    def test_close_file_object(self):\n        \"\"\"When a file object is used instead of a numeric file descriptor,\n        the object should be closed (by IOLoop.close(all_fds=True),\n        not just the fd.\n        \"\"\"\n        # Use a socket since they are supported by IOLoop on all platforms.\n        # Unfortunately, sockets don't support the .closed attribute for\n        # inspecting their close status, so we must use a wrapper.\n        class SocketWrapper(object):\n            def __init__(self, sockobj):\n                self.sockobj = sockobj\n                self.closed = False\n\n            def fileno(self):\n                return self.sockobj.fileno()\n\n            def close(self):\n                self.closed = True\n                self.sockobj.close()\n        sockobj, port = bind_unused_port()\n        socket_wrapper = SocketWrapper(sockobj)\n        io_loop = IOLoop()\n        io_loop.add_handler(socket_wrapper, lambda fd, events: None,\n                            IOLoop.READ)\n        io_loop.close(all_fds=True)\n        self.assertTrue(socket_wrapper.closed)\n\n    def test_handler_callback_file_object(self):\n        \"\"\"The handler callback receives the same fd object it passed in.\"\"\"\n        server_sock, port = bind_unused_port()\n        fds = []\n\n        def handle_connection(fd, events):\n            fds.append(fd)\n            conn, addr = server_sock.accept()\n            conn.close()\n            self.stop()\n        self.io_loop.add_handler(server_sock, handle_connection, IOLoop.READ)\n        with contextlib.closing(socket.socket()) as client_sock:\n            client_sock.connect(('127.0.0.1', port))\n            self.wait()\n        self.io_loop.remove_handler(server_sock)\n        self.io_loop.add_handler(server_sock.fileno(), handle_connection,\n                                 IOLoop.READ)\n        with contextlib.closing(socket.socket()) as client_sock:\n            client_sock.connect(('127.0.0.1', port))\n            self.wait()\n        self.assertIs(fds[0], server_sock)\n        self.assertEqual(fds[1], server_sock.fileno())\n        self.io_loop.remove_handler(server_sock.fileno())\n        server_sock.close()\n\n    def test_mixed_fd_fileobj(self):\n        server_sock, port = bind_unused_port()\n\n        def f(fd, events):\n            pass\n        self.io_loop.add_handler(server_sock, f, IOLoop.READ)\n        with self.assertRaises(Exception):\n            # The exact error is unspecified - some implementations use\n            # IOError, others use ValueError.\n            self.io_loop.add_handler(server_sock.fileno(), f, IOLoop.READ)\n        self.io_loop.remove_handler(server_sock.fileno())\n        server_sock.close()\n\n    def test_reentrant(self):\n        \"\"\"Calling start() twice should raise an error, not deadlock.\"\"\"\n        returned_from_start = [False]\n        got_exception = [False]\n\n        def callback():\n            try:\n                self.io_loop.start()\n                returned_from_start[0] = True\n            except Exception:\n                got_exception[0] = True\n            self.stop()\n        self.io_loop.add_callback(callback)\n        self.wait()\n        self.assertTrue(got_exception[0])\n        self.assertFalse(returned_from_start[0])\n\n    def test_exception_logging(self):\n        \"\"\"Uncaught exceptions get logged by the IOLoop.\"\"\"\n        # Use a NullContext to keep the exception from being caught by\n        # AsyncTestCase.\n        with NullContext():\n            self.io_loop.add_callback(lambda: 1 / 0)\n            self.io_loop.add_callback(self.stop)\n            with ExpectLog(app_log, \"Exception in callback\"):\n                self.wait()\n\n    def test_exception_logging_future(self):\n        \"\"\"The IOLoop examines exceptions from Futures and logs them.\"\"\"\n        with NullContext():\n            @gen.coroutine\n            def callback():\n                self.io_loop.add_callback(self.stop)\n                1 / 0\n            self.io_loop.add_callback(callback)\n            with ExpectLog(app_log, \"Exception in callback\"):\n                self.wait()\n\n    @skipBefore35\n    def test_exception_logging_native_coro(self):\n        \"\"\"The IOLoop examines exceptions from awaitables and logs them.\"\"\"\n        namespace = exec_test(globals(), locals(), \"\"\"\n        async def callback():\n            # Stop the IOLoop two iterations after raising an exception\n            # to give the exception time to be logged.\n            self.io_loop.add_callback(self.io_loop.add_callback, self.stop)\n            1 / 0\n        \"\"\")\n        with NullContext():\n            self.io_loop.add_callback(namespace[\"callback\"])\n            with ExpectLog(app_log, \"Exception in callback\"):\n                self.wait()\n\n    def test_spawn_callback(self):\n        # An added callback runs in the test's stack_context, so will be\n        # re-raised in wait().\n        self.io_loop.add_callback(lambda: 1 / 0)\n        with self.assertRaises(ZeroDivisionError):\n            self.wait()\n        # A spawned callback is run directly on the IOLoop, so it will be\n        # logged without stopping the test.\n        self.io_loop.spawn_callback(lambda: 1 / 0)\n        self.io_loop.add_callback(self.stop)\n        with ExpectLog(app_log, \"Exception in callback\"):\n            self.wait()\n\n    @skipIfNonUnix\n    def test_remove_handler_from_handler(self):\n        # Create two sockets with simultaneous read events.\n        client, server = socket.socketpair()\n        try:\n            client.send(b'abc')\n            server.send(b'abc')\n\n            # After reading from one fd, remove the other from the IOLoop.\n            chunks = []\n\n            def handle_read(fd, events):\n                chunks.append(fd.recv(1024))\n                if fd is client:\n                    self.io_loop.remove_handler(server)\n                else:\n                    self.io_loop.remove_handler(client)\n            self.io_loop.add_handler(client, handle_read, self.io_loop.READ)\n            self.io_loop.add_handler(server, handle_read, self.io_loop.READ)\n            self.io_loop.call_later(0.1, self.stop)\n            self.wait()\n\n            # Only one fd was read; the other was cleanly removed.\n            self.assertEqual(chunks, [b'abc'])\n        finally:\n            client.close()\n            server.close()\n\n\n# Deliberately not a subclass of AsyncTestCase so the IOLoop isn't\n# automatically set as current.\nclass TestIOLoopCurrent(unittest.TestCase):\n    def setUp(self):\n        self.io_loop = None\n        IOLoop.clear_current()\n\n    def tearDown(self):\n        if self.io_loop is not None:\n            self.io_loop.close()\n\n    def test_default_current(self):\n        self.io_loop = IOLoop()\n        # The first IOLoop with default arguments is made current.\n        self.assertIs(self.io_loop, IOLoop.current())\n        # A second IOLoop can be created but is not made current.\n        io_loop2 = IOLoop()\n        self.assertIs(self.io_loop, IOLoop.current())\n        io_loop2.close()\n\n    def test_non_current(self):\n        self.io_loop = IOLoop(make_current=False)\n        # The new IOLoop is not initially made current.\n        self.assertIsNone(IOLoop.current(instance=False))\n        # Starting the IOLoop makes it current, and stopping the loop\n        # makes it non-current. This process is repeatable.\n        for i in range(3):\n            def f():\n                self.current_io_loop = IOLoop.current()\n                self.io_loop.stop()\n            self.io_loop.add_callback(f)\n            self.io_loop.start()\n            self.assertIs(self.current_io_loop, self.io_loop)\n            # Now that the loop is stopped, it is no longer current.\n            self.assertIsNone(IOLoop.current(instance=False))\n\n    def test_force_current(self):\n        self.io_loop = IOLoop(make_current=True)\n        self.assertIs(self.io_loop, IOLoop.current())\n        with self.assertRaises(RuntimeError):\n            # A second make_current=True construction cannot succeed.\n            IOLoop(make_current=True)\n        # current() was not affected by the failed construction.\n        self.assertIs(self.io_loop, IOLoop.current())\n\n\nclass TestIOLoopCurrentAsync(AsyncTestCase):\n    @gen_test\n    def test_clear_without_current(self):\n        # If there is no current IOLoop, clear_current is a no-op (but\n        # should not fail). Use a thread so we see the threading.Local\n        # in a pristine state.\n        with ThreadPoolExecutor(1) as e:\n            yield e.submit(IOLoop.clear_current)\n\n\nclass TestIOLoopAddCallback(AsyncTestCase):\n    def setUp(self):\n        super(TestIOLoopAddCallback, self).setUp()\n        self.active_contexts = []\n\n    def add_callback(self, callback, *args, **kwargs):\n        self.io_loop.add_callback(callback, *args, **kwargs)\n\n    @contextlib.contextmanager\n    def context(self, name):\n        self.active_contexts.append(name)\n        yield\n        self.assertEqual(self.active_contexts.pop(), name)\n\n    def test_pre_wrap(self):\n        # A pre-wrapped callback is run in the context in which it was\n        # wrapped, not when it was added to the IOLoop.\n        def f1():\n            self.assertIn('c1', self.active_contexts)\n            self.assertNotIn('c2', self.active_contexts)\n            self.stop()\n\n        with StackContext(functools.partial(self.context, 'c1')):\n            wrapped = wrap(f1)\n\n        with StackContext(functools.partial(self.context, 'c2')):\n            self.add_callback(wrapped)\n\n        self.wait()\n\n    def test_pre_wrap_with_args(self):\n        # Same as test_pre_wrap, but the function takes arguments.\n        # Implementation note: The function must not be wrapped in a\n        # functools.partial until after it has been passed through\n        # stack_context.wrap\n        def f1(foo, bar):\n            self.assertIn('c1', self.active_contexts)\n            self.assertNotIn('c2', self.active_contexts)\n            self.stop((foo, bar))\n\n        with StackContext(functools.partial(self.context, 'c1')):\n            wrapped = wrap(f1)\n\n        with StackContext(functools.partial(self.context, 'c2')):\n            self.add_callback(wrapped, 1, bar=2)\n\n        result = self.wait()\n        self.assertEqual(result, (1, 2))\n\n\nclass TestIOLoopAddCallbackFromSignal(TestIOLoopAddCallback):\n    # Repeat the add_callback tests using add_callback_from_signal\n    def add_callback(self, callback, *args, **kwargs):\n        self.io_loop.add_callback_from_signal(callback, *args, **kwargs)\n\n\n@unittest.skipIf(futures is None, \"futures module not present\")\nclass TestIOLoopFutures(AsyncTestCase):\n    def test_add_future_threads(self):\n        with futures.ThreadPoolExecutor(1) as pool:\n            self.io_loop.add_future(pool.submit(lambda: None),\n                                    lambda future: self.stop(future))\n            future = self.wait()\n            self.assertTrue(future.done())\n            self.assertTrue(future.result() is None)\n\n    def test_add_future_stack_context(self):\n        ready = threading.Event()\n\n        def task():\n            # we must wait for the ioloop callback to be scheduled before\n            # the task completes to ensure that add_future adds the callback\n            # asynchronously (which is the scenario in which capturing\n            # the stack_context matters)\n            ready.wait(1)\n            assert ready.isSet(), \"timed out\"\n            raise Exception(\"worker\")\n\n        def callback(future):\n            self.future = future\n            raise Exception(\"callback\")\n\n        def handle_exception(typ, value, traceback):\n            self.exception = value\n            self.stop()\n            return True\n\n        # stack_context propagates to the ioloop callback, but the worker\n        # task just has its exceptions caught and saved in the Future.\n        with futures.ThreadPoolExecutor(1) as pool:\n            with ExceptionStackContext(handle_exception):\n                self.io_loop.add_future(pool.submit(task), callback)\n            ready.set()\n        self.wait()\n\n        self.assertEqual(self.exception.args[0], \"callback\")\n        self.assertEqual(self.future.exception().args[0], \"worker\")\n\n    @gen_test\n    def test_run_in_executor_gen(self):\n        event1 = threading.Event()\n        event2 = threading.Event()\n\n        def sync_func(self_event, other_event):\n            self_event.set()\n            other_event.wait()\n            # Note that return value doesn't actually do anything,\n            # it is just passed through to our final assertion to\n            # make sure it is passed through properly.\n            return self_event\n\n        # Run two synchronous functions, which would deadlock if not\n        # run in parallel.\n        res = yield [\n            IOLoop.current().run_in_executor(None, sync_func, event1, event2),\n            IOLoop.current().run_in_executor(None, sync_func, event2, event1)\n        ]\n\n        self.assertEqual([event1, event2], res)\n\n    @skipBefore35\n    @gen_test\n    def test_run_in_executor_native(self):\n        event1 = threading.Event()\n        event2 = threading.Event()\n\n        def sync_func(self_event, other_event):\n            self_event.set()\n            other_event.wait()\n            return self_event\n\n        # Go through an async wrapper to ensure that the result of\n        # run_in_executor works with await and not just gen.coroutine\n        # (simply passing the underlying concurrrent future would do that).\n        namespace = exec_test(globals(), locals(), \"\"\"\n            async def async_wrapper(self_event, other_event):\n                return await IOLoop.current().run_in_executor(\n                    None, sync_func, self_event, other_event)\n        \"\"\")\n\n        res = yield [\n            namespace[\"async_wrapper\"](event1, event2),\n            namespace[\"async_wrapper\"](event2, event1)\n        ]\n\n        self.assertEqual([event1, event2], res)\n\n    @gen_test\n    def test_set_default_executor(self):\n        count = [0]\n\n        class MyExecutor(futures.ThreadPoolExecutor):\n            def submit(self, func, *args):\n                count[0] += 1\n                return super(MyExecutor, self).submit(func, *args)\n\n        event = threading.Event()\n\n        def sync_func():\n            event.set()\n\n        executor = MyExecutor(1)\n        loop = IOLoop.current()\n        loop.set_default_executor(executor)\n        yield loop.run_in_executor(None, sync_func)\n        self.assertEqual(1, count[0])\n        self.assertTrue(event.is_set())\n\n\nclass TestIOLoopRunSync(unittest.TestCase):\n    def setUp(self):\n        self.io_loop = IOLoop()\n\n    def tearDown(self):\n        self.io_loop.close()\n\n    def test_sync_result(self):\n        with self.assertRaises(gen.BadYieldError):\n            self.io_loop.run_sync(lambda: 42)\n\n    def test_sync_exception(self):\n        with self.assertRaises(ZeroDivisionError):\n            self.io_loop.run_sync(lambda: 1 / 0)\n\n    def test_async_result(self):\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            raise gen.Return(42)\n        self.assertEqual(self.io_loop.run_sync(f), 42)\n\n    def test_async_exception(self):\n        @gen.coroutine\n        def f():\n            yield gen.moment\n            1 / 0\n        with self.assertRaises(ZeroDivisionError):\n            self.io_loop.run_sync(f)\n\n    def test_current(self):\n        def f():\n            self.assertIs(IOLoop.current(), self.io_loop)\n        self.io_loop.run_sync(f)\n\n    def test_timeout(self):\n        @gen.coroutine\n        def f():\n            yield gen.sleep(1)\n        self.assertRaises(TimeoutError, self.io_loop.run_sync, f, timeout=0.01)\n\n    @skipBefore35\n    def test_native_coroutine(self):\n        @gen.coroutine\n        def f1():\n            yield gen.moment\n\n        namespace = exec_test(globals(), locals(), \"\"\"\n        async def f2():\n            await f1()\n        \"\"\")\n        self.io_loop.run_sync(namespace['f2'])\n\n\n@unittest.skipIf(asyncio is not None,\n                 'IOLoop configuration not available')\nclass TestPeriodicCallback(unittest.TestCase):\n    def setUp(self):\n        self.io_loop = FakeTimeIOLoop()\n        self.io_loop.make_current()\n\n    def tearDown(self):\n        self.io_loop.close()\n\n    def test_basic(self):\n        calls = []\n\n        def cb():\n            calls.append(self.io_loop.time())\n        pc = PeriodicCallback(cb, 10000)\n        pc.start()\n        self.io_loop.call_later(50, self.io_loop.stop)\n        self.io_loop.start()\n        self.assertEqual(calls, [1010, 1020, 1030, 1040, 1050])\n\n    def test_overrun(self):\n        sleep_durations = [9, 9, 10, 11, 20, 20, 35, 35, 0, 0]\n        expected = [\n            1010, 1020, 1030,  # first 3 calls on schedule\n            1050, 1070,  # next 2 delayed one cycle\n            1100, 1130,  # next 2 delayed 2 cycles\n            1170, 1210,  # next 2 delayed 3 cycles\n            1220, 1230,  # then back on schedule.\n        ]\n        calls = []\n\n        def cb():\n            calls.append(self.io_loop.time())\n            if not sleep_durations:\n                self.io_loop.stop()\n                return\n            self.io_loop.sleep(sleep_durations.pop(0))\n        pc = PeriodicCallback(cb, 10000)\n        pc.start()\n        self.io_loop.start()\n        self.assertEqual(calls, expected)\n\n    def test_io_loop_set_at_start(self):\n        # Check PeriodicCallback uses the current IOLoop at start() time,\n        # not at instantiation time.\n        calls = []\n        io_loop = FakeTimeIOLoop()\n\n        def cb():\n            calls.append(io_loop.time())\n        pc = PeriodicCallback(cb, 10000)\n        io_loop.make_current()\n        pc.start()\n        io_loop.call_later(50, io_loop.stop)\n        io_loop.start()\n        self.assertEqual(calls, [1010, 1020, 1030, 1040, 1050])\n        io_loop.close()\n\n\nclass TestPeriodicCallbackMath(unittest.TestCase):\n    def simulate_calls(self, pc, durations):\n        \"\"\"Simulate a series of calls to the PeriodicCallback.\n\n        Pass a list of call durations in seconds. This method\n        returns the times at which each call would be made.\n        \"\"\"\n        calls = []\n        now = 1000\n        pc._next_timeout = now\n        for d in durations:\n            pc._update_next(now)\n            calls.append(pc._next_timeout)\n            now = pc._next_timeout + d\n        return calls\n\n    def test_basic(self):\n        pc = PeriodicCallback(None, 10000)\n        self.assertEqual(self.simulate_calls(pc, [0] * 5),\n                         [1010, 1020, 1030, 1040, 1050])\n\n    def test_overrun(self):\n        # If a call runs for too long, we skip entire cycles to get\n        # back on schedule.\n        call_durations = [9, 9, 10, 11, 20, 20, 35, 35, 0, 0, 0]\n        expected = [\n            1010, 1020, 1030,  # first 3 calls on schedule\n            1050, 1070,  # next 2 delayed one cycle\n            1100, 1130,  # next 2 delayed 2 cycles\n            1170, 1210,  # next 2 delayed 3 cycles\n            1220, 1230,  # then back on schedule.\n        ]\n\n        pc = PeriodicCallback(None, 10000)\n        self.assertEqual(self.simulate_calls(pc, call_durations),\n                         expected)\n\n\nclass TestIOLoopConfiguration(unittest.TestCase):\n    def run_python(self, *statements):\n        statements = [\n            'from tornado.ioloop import IOLoop, PollIOLoop',\n            'classname = lambda x: x.__class__.__name__',\n        ] + list(statements)\n        args = [sys.executable, '-c', '; '.join(statements)]\n        return native_str(subprocess.check_output(args)).strip()\n\n    def test_default(self):\n        if asyncio is not None:\n            # When asyncio is available, it is used by default.\n            cls = self.run_python('print(classname(IOLoop.current()))')\n            self.assertEqual(cls, 'AsyncIOMainLoop')\n            cls = self.run_python('print(classname(IOLoop()))')\n            self.assertEqual(cls, 'AsyncIOLoop')\n        else:\n            # Otherwise, the default is a subclass of PollIOLoop\n            is_poll = self.run_python(\n                'print(isinstance(IOLoop.current(), PollIOLoop))')\n            self.assertEqual(is_poll, 'True')\n\n    @unittest.skipIf(asyncio is not None,\n                     \"IOLoop configuration not available\")\n    def test_explicit_select(self):\n        # SelectIOLoop can always be configured explicitly.\n        default_class = self.run_python(\n            'IOLoop.configure(\"tornado.platform.select.SelectIOLoop\")',\n            'print(classname(IOLoop.current()))')\n        self.assertEqual(default_class, 'SelectIOLoop')\n\n    @unittest.skipIf(asyncio is None, \"asyncio module not present\")\n    def test_asyncio(self):\n        cls = self.run_python(\n            'IOLoop.configure(\"tornado.platform.asyncio.AsyncIOLoop\")',\n            'print(classname(IOLoop.current()))')\n        self.assertEqual(cls, 'AsyncIOMainLoop')\n\n    @unittest.skipIf(asyncio is None, \"asyncio module not present\")\n    def test_asyncio_main(self):\n        cls = self.run_python(\n            'from tornado.platform.asyncio import AsyncIOMainLoop',\n            'AsyncIOMainLoop().install()',\n            'print(classname(IOLoop.current()))')\n        self.assertEqual(cls, 'AsyncIOMainLoop')\n\n    @unittest.skipIf(twisted is None, \"twisted module not present\")\n    @unittest.skipIf(asyncio is not None,\n                     \"IOLoop configuration not available\")\n    def test_twisted(self):\n        cls = self.run_python(\n            'from tornado.platform.twisted import TwistedIOLoop',\n            'TwistedIOLoop().install()',\n            'print(classname(IOLoop.current()))')\n        self.assertEqual(cls, 'TwistedIOLoop')\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
        "#!/usr/bin/env python\nimport unittest\nimport sys\nimport time\nimport traceback\nimport platform\nimport os\n\n\nclass PytestLikeResult(unittest.TestResult):\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.start_time = None\n        # Store (test, outcome, info) for each test:\n        #   outcome ∈ { \"passed\", \"failed\", \"error\", \"skipped\" }\n        #   info can hold the exception or skip reason, etc.\n        self.results = []\n\n    def startTestRun(self):\n        \"\"\"Called once before all tests.\"\"\"\n        self.start_time = time.time()\n        # Print a header similar to pytest\n        print(\"=\" * 29 + \" test session starts \" + \"=\" * 29)\n        # You can customize the platform/versions/paths as you like:\n        print(\n            f\"platform {platform.system().lower()} -- Python {platform.python_version()}\"\n        )\n        print(f\"rootdir: {os.path.abspath(os.curdir)}\")\n\n    def stopTestRun(self):\n        \"\"\"Called once after all tests are done.\"\"\"\n        elapsed = time.time() - self.start_time\n        print()  # blank line after final dot\n\n        # Summarize\n        ntests = len(self.results)\n        print(f\"collected {ntests} items\")\n\n        # Show details of failures/errors\n        failures = [r for r in self.results if r[1] == \"failed\"]\n        errors = [r for r in self.results if r[1] == \"error\"]\n\n        if failures:\n            print(\"\\n\" + \"=\" * 35 + \" FAILURES \" + \"=\" * 35)\n            for test, outcome, err_info in failures:\n                test = test.split(\"::\")\n                if len(test) == 3:\n                    test = f\"{test[1]}.{test[2]}\"\n                else:\n                    test = f\"{test[1]}\"\n                print(f\"__________ {test} __________\")\n                self._print_traceback(err_info)\n        if errors:\n            print(\"\\n\" + \"=\" * 35 + \" ERRORS \" + \"=\" * 37)\n            for test, outcome, err_info in errors:\n                test = test.split(\"::\")\n                if len(test) == 3:\n                    test = f\"{test[1]}.{test[2]}\"\n                else:\n                    test = f\"{test[1]}\"\n                print(f\"__________ {test} __________\")\n                self._print_traceback(err_info)\n\n        # Optional short summary lines for passes/fails/skips\n        print(\"\\n==================== short test summary info ====================\")\n        for test, outcome, info in self.results:\n            if outcome in (\"passed\", \"failed\", \"error\", \"skipped\"):\n                print(f\"{outcome.upper()} {test}\")\n\n        # Final one-line summary: “1 failed, 1 errors, 10 passed in 2.04s”\n        passed_count = sum(1 for r in self.results if r[1] == \"passed\")\n        failed_count = len(failures)\n        error_count = len(errors)\n        skipped_count = sum(1 for r in self.results if r[1] == \"skipped\")\n\n        summary_bits = []\n        if failed_count:\n            summary_bits.append(f\"{failed_count} failed\")\n        if error_count:\n            summary_bits.append(f\"{error_count} error{'s' if error_count != 1 else ''}\")\n        if passed_count:\n            summary_bits.append(f\"{passed_count} passed\")\n        if skipped_count:\n            summary_bits.append(f\"{skipped_count} skipped\")\n\n        summary_str = \", \".join(summary_bits) if summary_bits else \"no tests run\"\n        print(\n            f\"=================== {summary_str} in {elapsed:.2f}s ===================\"\n        )\n\n    def startTest(self, test):\n        \"\"\"Called right before each test method.\"\"\"\n        super().startTest(test)\n        # Print a dot or some indicator\n        print(\".\", end=\"\", flush=True)\n\n    def addSuccess(self, test):\n        super().addSuccess(test)\n        self.results.append((self._test_id(test), \"passed\", None))\n\n    def addFailure(self, test, err):\n        super().addFailure(test, err)\n        self.results.append((self._test_id(test), \"failed\", err))\n\n    def addError(self, test, err):\n        super().addError(test, err)\n        self.results.append((self._test_id(test), \"error\", err))\n\n    def addSkip(self, test, reason):\n        super().addSkip(test, reason)\n        self.results.append((self._test_id(test), \"skipped\", reason))\n\n    def _print_traceback(self, err_info):\n        \"\"\"Helper to print the traceback like pytest does.\"\"\"\n        if isinstance(err_info, tuple) and len(err_info) == 3:\n            exc_type, exc_value, tb = err_info\n            traceback.print_exception(exc_type, exc_value, tb, file=sys.stdout)\n        else:\n            print(str(err_info))\n\n    def _test_id(self, test):\n        try:\n            return f\"{test.__class__.__module__}::{test.__class__.__name__}::{test._testMethodName}\"\n        except AttributeError:\n            # Fallback for _ErrorHolder objects\n            return f\"{test.__class__.__module__}::{test.__class__.__name__}\"\n\n\nclass PytestLikeRunner(unittest.TextTestRunner):\n    \"\"\"A custom TextTestRunner that uses the PytestLikeResult.\"\"\"\n\n    resultclass = PytestLikeResult\n\n    def run(self, test):\n        result = self._makeResult()\n        # Overriding run to ensure we call startTestRun/stopTestRun\n        result.startTestRun()\n        test(result)\n        result.stopTestRun()\n        return result\n\n    def tearDown(self):\n        # Reset signal handlers\n        from twisted.internet import reactor\n\n        reactor.removeAll()\n        reactor.stop()\n        super().tearDown()\n\n\ndef main():\n    loader = unittest.TestLoader()\n    suite = loader.discover(\".\", pattern=\"test_*.py\")  # discover tests in r2e_tests/\n    runner = PytestLikeRunner(verbosity=0)\n    result = runner.run(suite)\n    # Exit with code 0 if all tests passed/skipped, 1 if there were fails/errors\n    sys.exit(not result.wasSuccessful())\n\n\nif __name__ == \"__main__\":\n    main()\n"
    ],
    "test_file_names": [
        "test_1.py",
        "tornado_unittest_runner.py"
    ],
    "setup_res_code": 0,
    "setup_res_stdout": "",
    "setup_res_stderr": "Using CPython 3.9.21\nCreating virtual environment at: .venv\nActivate with: source .venv/bin/activate\nResolved 1 package in 1.00s\nPrepared 1 package in 1.16s\nInstalled 1 package in 1ms\n + tornado==5.1.dev1 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2d4053daa56c609d642b214399e046671d4a593e)\nResolved 29 packages in 17ms\nInstalled 29 packages in 180ms\n + attrs==24.3.0\n + automat==24.8.1\n + cachetools==5.5.0\n + cffi==1.17.1\n + chardet==5.2.0\n + colorama==0.4.6\n + constantly==23.10.4\n + distlib==0.3.9\n + exceptiongroup==1.2.2\n + filelock==3.16.1\n + hyperlink==21.0.0\n + idna==3.10\n + incremental==24.7.2\n + iniconfig==2.0.0\n + packaging==24.2\n + platformdirs==4.3.6\n + pluggy==1.5.0\n + pycares==4.5.0\n + pycparser==2.22\n + pycurl==7.45.4\n + pyproject-api==1.8.0\n + pytest==8.3.4\n + setuptools==75.6.0\n + tomli==2.2.1\n + tox==4.23.2\n + twisted==24.11.0\n + typing-extensions==4.12.2\n + virtualenv==20.28.0\n + zope-interface==7.2\n",
    "new_commit_res_code": 0,
    "new_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2d4053daa56c609d642b214399e046671d4a593e\n.........................................................\ncollected 57 items\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::TestIOLoop::test_add_callback_from_signal\nPASSED r2e_tests.test_1::TestIOLoop::test_add_callback_from_signal_other_thread\nPASSED r2e_tests.test_1::TestIOLoop::test_add_callback_return_sequence\nPASSED r2e_tests.test_1::TestIOLoop::test_add_callback_wakeup\nPASSED r2e_tests.test_1::TestIOLoop::test_add_callback_wakeup_other_thread\nPASSED r2e_tests.test_1::TestIOLoop::test_add_callback_while_closing\nPASSED r2e_tests.test_1::TestIOLoop::test_add_timeout_return\nPASSED r2e_tests.test_1::TestIOLoop::test_add_timeout_timedelta\nPASSED r2e_tests.test_1::TestIOLoop::test_call_at_return\nPASSED r2e_tests.test_1::TestIOLoop::test_call_later_return\nPASSED r2e_tests.test_1::TestIOLoop::test_close_file_object\nPASSED r2e_tests.test_1::TestIOLoop::test_exception_logging\nPASSED r2e_tests.test_1::TestIOLoop::test_exception_logging_future\nPASSED r2e_tests.test_1::TestIOLoop::test_exception_logging_native_coro\nPASSED r2e_tests.test_1::TestIOLoop::test_handle_callback_exception\nPASSED r2e_tests.test_1::TestIOLoop::test_handler_callback_file_object\nPASSED r2e_tests.test_1::TestIOLoop::test_mixed_fd_fileobj\nPASSED r2e_tests.test_1::TestIOLoop::test_multiple_add\nPASSED r2e_tests.test_1::TestIOLoop::test_read_while_writeable\nPASSED r2e_tests.test_1::TestIOLoop::test_reentrant\nPASSED r2e_tests.test_1::TestIOLoop::test_remove_handler_from_handler\nPASSED r2e_tests.test_1::TestIOLoop::test_remove_timeout_after_fire\nPASSED r2e_tests.test_1::TestIOLoop::test_remove_timeout_cleanup\nPASSED r2e_tests.test_1::TestIOLoop::test_remove_timeout_from_timeout\nPASSED r2e_tests.test_1::TestIOLoop::test_remove_without_add\nPASSED r2e_tests.test_1::TestIOLoop::test_spawn_callback\nPASSED r2e_tests.test_1::TestIOLoop::test_timeout_with_arguments\nPASSED r2e_tests.test_1::TestIOLoopAddCallback::test_pre_wrap\nPASSED r2e_tests.test_1::TestIOLoopAddCallback::test_pre_wrap_with_args\nPASSED r2e_tests.test_1::TestIOLoopAddCallbackFromSignal::test_pre_wrap\nPASSED r2e_tests.test_1::TestIOLoopAddCallbackFromSignal::test_pre_wrap_with_args\nPASSED r2e_tests.test_1::TestIOLoopConfiguration::test_asyncio\nPASSED r2e_tests.test_1::TestIOLoopConfiguration::test_asyncio_main\nPASSED r2e_tests.test_1::TestIOLoopConfiguration::test_default\nSKIPPED r2e_tests.test_1::TestIOLoopConfiguration::test_explicit_select\nSKIPPED r2e_tests.test_1::TestIOLoopConfiguration::test_twisted\nPASSED r2e_tests.test_1::TestIOLoopCurrent::test_default_current\nPASSED r2e_tests.test_1::TestIOLoopCurrent::test_force_current\nPASSED r2e_tests.test_1::TestIOLoopCurrent::test_non_current\nPASSED r2e_tests.test_1::TestIOLoopCurrentAsync::test_clear_without_current\nPASSED r2e_tests.test_1::TestIOLoopFutures::test_add_future_stack_context\nPASSED r2e_tests.test_1::TestIOLoopFutures::test_add_future_threads\nPASSED r2e_tests.test_1::TestIOLoopFutures::test_run_in_executor_gen\nPASSED r2e_tests.test_1::TestIOLoopFutures::test_run_in_executor_native\nPASSED r2e_tests.test_1::TestIOLoopFutures::test_set_default_executor\nPASSED r2e_tests.test_1::TestIOLoopRunSync::test_async_exception\nPASSED r2e_tests.test_1::TestIOLoopRunSync::test_async_result\nPASSED r2e_tests.test_1::TestIOLoopRunSync::test_current\nPASSED r2e_tests.test_1::TestIOLoopRunSync::test_native_coroutine\nPASSED r2e_tests.test_1::TestIOLoopRunSync::test_sync_exception\nPASSED r2e_tests.test_1::TestIOLoopRunSync::test_sync_result\nPASSED r2e_tests.test_1::TestIOLoopRunSync::test_timeout\nSKIPPED r2e_tests.test_1::TestPeriodicCallback::test_basic\nSKIPPED r2e_tests.test_1::TestPeriodicCallback::test_io_loop_set_at_start\nSKIPPED r2e_tests.test_1::TestPeriodicCallback::test_overrun\nPASSED r2e_tests.test_1::TestPeriodicCallbackMath::test_basic\nPASSED r2e_tests.test_1::TestPeriodicCallbackMath::test_overrun\n=================== 52 passed, 5 skipped in 0.55s ===================\n",
    "new_commit_res_stderr": "",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2d4053daa56c609d642b214399e046671d4a593e\n.........................................................\ncollected 57 items\n\n=================================== ERRORS =====================================\n__________ TestPeriodicCallbackMath.test_basic __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2d4053daa56c609d642b214399e046671d4a593e/r2e_tests/test_1.py\", line 810, in test_basic\n    self.assertEqual(self.simulate_calls(pc, [0] * 5),\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2d4053daa56c609d642b214399e046671d4a593e/r2e_tests/test_1.py\", line 803, in simulate_calls\n    pc._update_next(now)\nAttributeError: 'PeriodicCallback' object has no attribute '_update_next'\n__________ TestPeriodicCallbackMath.test_overrun __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2d4053daa56c609d642b214399e046671d4a593e/r2e_tests/test_1.py\", line 826, in test_overrun\n    self.assertEqual(self.simulate_calls(pc, call_durations),\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_2d4053daa56c609d642b214399e046671d4a593e/r2e_tests/test_1.py\", line 803, in simulate_calls\n    pc._update_next(now)\nAttributeError: 'PeriodicCallback' object has no attribute '_update_next'\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::TestIOLoop::test_add_callback_from_signal\nPASSED r2e_tests.test_1::TestIOLoop::test_add_callback_from_signal_other_thread\nPASSED r2e_tests.test_1::TestIOLoop::test_add_callback_return_sequence\nPASSED r2e_tests.test_1::TestIOLoop::test_add_callback_wakeup\nPASSED r2e_tests.test_1::TestIOLoop::test_add_callback_wakeup_other_thread\nPASSED r2e_tests.test_1::TestIOLoop::test_add_callback_while_closing\nPASSED r2e_tests.test_1::TestIOLoop::test_add_timeout_return\nPASSED r2e_tests.test_1::TestIOLoop::test_add_timeout_timedelta\nPASSED r2e_tests.test_1::TestIOLoop::test_call_at_return\nPASSED r2e_tests.test_1::TestIOLoop::test_call_later_return\nPASSED r2e_tests.test_1::TestIOLoop::test_close_file_object\nPASSED r2e_tests.test_1::TestIOLoop::test_exception_logging\nPASSED r2e_tests.test_1::TestIOLoop::test_exception_logging_future\nPASSED r2e_tests.test_1::TestIOLoop::test_exception_logging_native_coro\nPASSED r2e_tests.test_1::TestIOLoop::test_handle_callback_exception\nPASSED r2e_tests.test_1::TestIOLoop::test_handler_callback_file_object\nPASSED r2e_tests.test_1::TestIOLoop::test_mixed_fd_fileobj\nPASSED r2e_tests.test_1::TestIOLoop::test_multiple_add\nPASSED r2e_tests.test_1::TestIOLoop::test_read_while_writeable\nPASSED r2e_tests.test_1::TestIOLoop::test_reentrant\nPASSED r2e_tests.test_1::TestIOLoop::test_remove_handler_from_handler\nPASSED r2e_tests.test_1::TestIOLoop::test_remove_timeout_after_fire\nPASSED r2e_tests.test_1::TestIOLoop::test_remove_timeout_cleanup\nPASSED r2e_tests.test_1::TestIOLoop::test_remove_timeout_from_timeout\nPASSED r2e_tests.test_1::TestIOLoop::test_remove_without_add\nPASSED r2e_tests.test_1::TestIOLoop::test_spawn_callback\nPASSED r2e_tests.test_1::TestIOLoop::test_timeout_with_arguments\nPASSED r2e_tests.test_1::TestIOLoopAddCallback::test_pre_wrap\nPASSED r2e_tests.test_1::TestIOLoopAddCallback::test_pre_wrap_with_args\nPASSED r2e_tests.test_1::TestIOLoopAddCallbackFromSignal::test_pre_wrap\nPASSED r2e_tests.test_1::TestIOLoopAddCallbackFromSignal::test_pre_wrap_with_args\nPASSED r2e_tests.test_1::TestIOLoopConfiguration::test_asyncio\nPASSED r2e_tests.test_1::TestIOLoopConfiguration::test_asyncio_main\nPASSED r2e_tests.test_1::TestIOLoopConfiguration::test_default\nSKIPPED r2e_tests.test_1::TestIOLoopConfiguration::test_explicit_select\nSKIPPED r2e_tests.test_1::TestIOLoopConfiguration::test_twisted\nPASSED r2e_tests.test_1::TestIOLoopCurrent::test_default_current\nPASSED r2e_tests.test_1::TestIOLoopCurrent::test_force_current\nPASSED r2e_tests.test_1::TestIOLoopCurrent::test_non_current\nPASSED r2e_tests.test_1::TestIOLoopCurrentAsync::test_clear_without_current\nPASSED r2e_tests.test_1::TestIOLoopFutures::test_add_future_stack_context\nPASSED r2e_tests.test_1::TestIOLoopFutures::test_add_future_threads\nPASSED r2e_tests.test_1::TestIOLoopFutures::test_run_in_executor_gen\nPASSED r2e_tests.test_1::TestIOLoopFutures::test_run_in_executor_native\nPASSED r2e_tests.test_1::TestIOLoopFutures::test_set_default_executor\nPASSED r2e_tests.test_1::TestIOLoopRunSync::test_async_exception\nPASSED r2e_tests.test_1::TestIOLoopRunSync::test_async_result\nPASSED r2e_tests.test_1::TestIOLoopRunSync::test_current\nPASSED r2e_tests.test_1::TestIOLoopRunSync::test_native_coroutine\nPASSED r2e_tests.test_1::TestIOLoopRunSync::test_sync_exception\nPASSED r2e_tests.test_1::TestIOLoopRunSync::test_sync_result\nPASSED r2e_tests.test_1::TestIOLoopRunSync::test_timeout\nSKIPPED r2e_tests.test_1::TestPeriodicCallback::test_basic\nSKIPPED r2e_tests.test_1::TestPeriodicCallback::test_io_loop_set_at_start\nSKIPPED r2e_tests.test_1::TestPeriodicCallback::test_overrun\nERROR r2e_tests.test_1::TestPeriodicCallbackMath::test_basic\nERROR r2e_tests.test_1::TestPeriodicCallbackMath::test_overrun\n=================== 2 errors, 50 passed, 5 skipped in 0.53s ===================\n",
    "old_commit_res_stderr": ""
}
tornado/ioloop.py tornado/test/ioloop_test.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** `PeriodicCallback` Missing `_update_next` Method Causing Test Failures

**Description:**
When running tests designed to verify the mathematical calculations of `PeriodicCallback`, an `AttributeError` is raised because the `_update_next` method does not exist in the `PeriodicCallback` class. This prevents the tests from executing the intended logic separately from the IOLoop configuration.

**Example Code:**
```python
class TestPeriodicCallbackMath(unittest.TestCase):
    def simulate_calls(self, pc, durations):
        calls = []
        now = 1000
        pc._next_timeout = now
        for d in durations:
            pc._update_next(now)
            calls.append(pc._next_timeout)
            now = pc._next_timeout + d
        return calls

    def test_basic(self):
        pc = PeriodicCallback(None, 10000)
        self.simulate_calls(pc, [0] * 5)
```

**Expected Behavior:**
The `PeriodicCallback` class should include the `_update_next` method, allowing the mathematical scheduling logic to be tested independently. This method should correctly update the next timeout based on the current time and callback interval.

**Actual Behavior:**
Running the tests results in the following error:
```
AttributeError: 'PeriodicCallback' object has no attribute '_update_next'
```
This error prevents the math-related tests from executing, hindering the ability to verify the correctness of the periodic callback scheduling.

[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### tornado/ioloop.py
#
# Copyright 2009 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

"""An I/O event loop for non-blocking sockets.

On Python 3, `.IOLoop` is a wrapper around the `asyncio` event loop.

Typical applications will use a single `IOLoop` object, accessed via
`IOLoop.current` class method. The `IOLoop.start` method (or
equivalently, `asyncio.AbstractEventLoop.run_forever`) should usually
be called at the end of the ``main()`` function. Atypical applications
may use more than one `IOLoop`, such as one `IOLoop` per thread, or
per `unittest` case.

In addition to I/O events, the `IOLoop` can also schedule time-based
events. `IOLoop.add_timeout` is a non-blocking alternative to
`time.sleep`.

"""

from __future__ import absolute_import, division, print_function

import collections
import datetime
import errno
import functools
import heapq
import itertools
import logging
import numbers
import os
import select
import sys
import threading
import time
import traceback
import math

from tornado.concurrent import Future, is_future, chain_future, future_set_exc_info, future_add_done_callback  # noqa: E501
from tornado.log import app_log, gen_log
from tornado.platform.auto import set_close_exec, Waker
from tornado import stack_context
from tornado.util import (
    PY3, Configurable, errno_from_exception, timedelta_to_seconds,
    TimeoutError, unicode_type, import_object,
)

try:
    import signal
except ImportError:
    signal = None

try:
    from concurrent.futures import ThreadPoolExecutor
except ImportError:
    ThreadPoolExecutor = None

if PY3:
    import _thread as thread
else:
    import thread

try:
    import asyncio
except ImportError:
    asyncio = None


_POLL_TIMEOUT = 3600.0


class IOLoop(Configurable):
    """A level-triggered I/O loop.

    On Python 3, `IOLoop` is a wrapper around the `asyncio` event
    loop. On Python 2, it uses ``epoll`` (Linux) or ``kqueue`` (BSD
    and Mac OS X) if they are available, or else we fall back on
    select(). If you are implementing a system that needs to handle
    thousands of simultaneous connections, you should use a system
    that supports either ``epoll`` or ``kqueue``.

    Example usage for a simple TCP server:

    .. testcode::

        import errno
        import functools
        import socket

        import tornado.ioloop
        from tornado import gen
        from tornado.iostream import IOStream

        @gen.coroutine
        def handle_connection(connection, address):
            stream = IOStream(connection)
            message = yield stream.read_until_close()
            print("message from client:", message.decode().strip())

        def connection_ready(sock, fd, events):
            while True:
                try:
                    connection, address = sock.accept()
                except socket.error as e:
                    if e.args[0] not in (errno.EWOULDBLOCK, errno.EAGAIN):
                        raise
                    return
                connection.setblocking(0)
                handle_connection(connection, address)

        if __name__ == '__main__':
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            sock.setblocking(0)
            sock.bind(("", 8888))
            sock.listen(128)

            io_loop = tornado.ioloop.IOLoop.current()
            callback = functools.partial(connection_ready, sock)
            io_loop.add_handler(sock.fileno(), callback, io_loop.READ)
            io_loop.start()

    .. testoutput::
       :hide:

    By default, a newly-constructed `IOLoop` becomes the thread's current
    `IOLoop`, unless there already is a current `IOLoop`. This behavior
    can be controlled with the ``make_current`` argument to the `IOLoop`
    constructor: if ``make_current=True``, the new `IOLoop` will always
    try to become current and it raises an error if there is already a
    current instance. If ``make_current=False``, the new `IOLoop` will
    not try to become current.

    In general, an `IOLoop` cannot survive a fork or be shared across
    processes in any way. When multiple processes are being used, each
    process should create its own `IOLoop`, which also implies that
    any objects which depend on the `IOLoop` (such as
    `.AsyncHTTPClient`) must also be created in the child processes.
    As a guideline, anything that starts processes (including the
    `tornado.process` and `multiprocessing` modules) should do so as
    early as possible, ideally the first thing the application does
    after loading its configuration in ``main()``.

    .. versionchanged:: 4.2
       Added the ``make_current`` keyword argument to the `IOLoop`
       constructor.

    .. versionchanged:: 5.0

       Uses the `asyncio` event loop by default. The
       ``IOLoop.configure`` method cannot be used on Python 3 except
       to redundantly specify the `asyncio` event loop.

    """
    # Constants from the epoll module
    _EPOLLIN = 0x001
    _EPOLLPRI = 0x002
    _EPOLLOUT = 0x004
    _EPOLLERR = 0x008
    _EPOLLHUP = 0x010
    _EPOLLRDHUP = 0x2000
    _EPOLLONESHOT = (1 << 30)
    _EPOLLET = (1 << 31)

    # Our events map exactly to the epoll events
    NONE = 0
    READ = _EPOLLIN
    WRITE = _EPOLLOUT
    ERROR = _EPOLLERR | _EPOLLHUP

    # In Python 2, _current.instance points to the current IOLoop.
    _current = threading.local()

    # In Python 3, _ioloop_for_asyncio maps from asyncio loops to IOLoops.
    _ioloop_for_asyncio = dict()

    @classmethod
    def configure(cls, impl, **kwargs):
        if asyncio is not None:
            from tornado.platform.asyncio import BaseAsyncIOLoop

            if isinstance(impl, (str, unicode_type)):
                impl = import_object(impl)
            if not issubclass(impl, BaseAsyncIOLoop):
                raise RuntimeError(
                    "only AsyncIOLoop is allowed when asyncio is available")
        super(IOLoop, cls).configure(impl, **kwargs)

    @staticmethod
    def instance():
        """Deprecated alias for `IOLoop.current()`.

        .. versionchanged:: 5.0

           Previously, this method returned a global singleton
           `IOLoop`, in contrast with the per-thread `IOLoop` returned
           by `current()`. In nearly all cases the two were the same
           (when they differed, it was generally used from non-Tornado
           threads to communicate back to the main thread's `IOLoop`).
           This distinction is not present in `asyncio`, so in order
           to facilitate integration with that package `instance()`
           was changed to be an alias to `current()`. Applications
           using the cross-thread communications aspect of
           `instance()` should instead set their own global variable
           to point to the `IOLoop` they want to use.

        .. deprecated:: 5.0
        """
        return IOLoop.current()

    def install(self):
        """Deprecated alias for `make_current()`.

        .. versionchanged:: 5.0

           Previously, this method would set this `IOLoop` as the
           global singleton used by `IOLoop.instance()`. Now that
           `instance()` is an alias for `current()`, `install()`
           is an alias for `make_current()`.

        .. deprecated:: 5.0
        """
        self.make_current()

    @staticmethod
    def clear_instance():
        """Deprecated alias for `clear_current()`.

        .. versionchanged:: 5.0

           Previously, this method would clear the `IOLoop` used as
           the global singleton by `IOLoop.instance()`. Now that
           `instance()` is an alias for `current()`,
           `clear_instance()` is an alias for `clear_current()`.

        .. deprecated:: 5.0

        """
        IOLoop.clear_current()

    @staticmethod
    def current(instance=True):
        """Returns the current thread's `IOLoop`.

        If an `IOLoop` is currently running or has been marked as
        current by `make_current`, returns that instance.  If there is
        no current `IOLoop` and ``instance`` is true, creates one.

        .. versionchanged:: 4.1
           Added ``instance`` argument to control the fallback to
           `IOLoop.instance()`.
        .. versionchanged:: 5.0
           On Python 3, control of the current `IOLoop` is delegated
           to `asyncio`, with this and other methods as pass-through accessors.
           The ``instance`` argument now controls whether an `IOLoop`
           is created automatically when there is none, instead of
           whether we fall back to `IOLoop.instance()` (which is now
           an alias for this method). ``instance=False`` is deprecated,
           since even if we do not create an `IOLoop`, this method
           may initialize the asyncio loop.
        """
        if asyncio is None:
            current = getattr(IOLoop._current, "instance", None)
            if current is None and instance:
                current = IOLoop()
                if IOLoop._current.instance is not current:
                    raise RuntimeError("new IOLoop did not become current")
        else:
            try:
                loop = asyncio.get_event_loop()
            except (RuntimeError, AssertionError):
                if not instance:
                    return None
                raise
            try:
                return IOLoop._ioloop_for_asyncio[loop]
            except KeyError:
                if instance:
                    from tornado.platform.asyncio import AsyncIOMainLoop
                    current = AsyncIOMainLoop(make_current=True)
                else:
                    current = None
        return current

    def make_current(self):
        """Makes this the `IOLoop` for the current thread.

        An `IOLoop` automatically becomes current for its thread
        when it is started, but it is sometimes useful to call
        `make_current` explicitly before starting the `IOLoop`,
        so that code run at startup time can find the right
        instance.

        .. versionchanged:: 4.1
           An `IOLoop` created while there is no current `IOLoop`
           will automatically become current.

        .. versionchanged:: 5.0
           This method also sets the current `asyncio` event loop.
        """
        # The asyncio event loops override this method.
        assert asyncio is None
        old = getattr(IOLoop._current, "instance", None)
        if old is not None:
            old.clear_current()
        IOLoop._current.instance = self

    @staticmethod
    def clear_current():
        """Clears the `IOLoop` for the current thread.

        Intended primarily for use by test frameworks in between tests.

        .. versionchanged:: 5.0
           This method also clears the current `asyncio` event loop.
        """
        old = IOLoop.current(instance=False)
        if old is not None:
            old._clear_current_hook()
        if asyncio is None:
            IOLoop._current.instance = None

    def _clear_current_hook(self):
        """Instance method called when an IOLoop ceases to be current.

        May be overridden by subclasses as a counterpart to make_current.
        """
        pass

    @classmethod
    def configurable_base(cls):
        return IOLoop

    @classmethod
    def configurable_default(cls):
        if asyncio is not None:
            from tornado.platform.asyncio import AsyncIOLoop
            return AsyncIOLoop
        return PollIOLoop

    def initialize(self, make_current=None):
        if make_current is None:
            if IOLoop.current(instance=False) is None:
                self.make_current()
        elif make_current:
            current = IOLoop.current(instance=False)
            # AsyncIO loops can already be current by this point.
            if current is not None and current is not self:
                raise RuntimeError("current IOLoop already exists")
            self.make_current()

    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 add_handler(self, fd, handler, events):
        """Registers the given handler to receive the given events for ``fd``.

        The ``fd`` argument may either be an integer file descriptor or
        a file-like object with a ``fileno()`` method (and optionally a
        ``close()`` method, which may be called when the `IOLoop` is shut
        down).

        The ``events`` argument is a bitwise or of the constants
        ``IOLoop.READ``, ``IOLoop.WRITE``, and ``IOLoop.ERROR``.

        When an event occurs, ``handler(fd, events)`` will be run.

        .. versionchanged:: 4.0
           Added the ability to pass file-like objects in addition to
           raw file descriptors.
        """
        raise NotImplementedError()

    def update_handler(self, fd, events):
        """Changes the events we listen for ``fd``.

        .. versionchanged:: 4.0
           Added the ability to pass file-like objects in addition to
           raw file descriptors.
        """
        raise NotImplementedError()

    def remove_handler(self, fd):
        """Stop listening for events on ``fd``.

        .. versionchanged:: 4.0
           Added the ability to pass file-like objects in addition to
           raw file descriptors.
        """
        raise NotImplementedError()

    def set_blocking_signal_threshold(self, seconds, action):
        """Sends a signal if the `IOLoop` is blocked for more than
        ``s`` seconds.

        Pass ``seconds=None`` to disable.  Requires Python 2.6 on a unixy
        platform.

        The action parameter is a Python signal handler.  Read the
        documentation for the `signal` module for more information.
        If ``action`` is None, the process will be killed if it is
        blocked for too long.

        .. deprecated:: 5.0

           Not implemented on the `asyncio` event loop. Use the environment
           variable ``PYTHONASYNCIODEBUG=1`` instead.
        """
        raise NotImplementedError()

    def set_blocking_log_threshold(self, seconds):
        """Logs a stack trace if the `IOLoop` is blocked for more than
        ``s`` seconds.

        Equivalent to ``set_blocking_signal_threshold(seconds,
        self.log_stack)``

        .. deprecated:: 5.0

           Not implemented on the `asyncio` event loop. Use the environment
           variable ``PYTHONASYNCIODEBUG=1`` instead.
        """
        self.set_blocking_signal_threshold(seconds, self.log_stack)

    def log_stack(self, signal, frame):
        """Signal handler to log the stack trace of the current thread.

        For use with `set_blocking_signal_threshold`.
        """
        gen_log.warning('IOLoop blocked for %f seconds in\n%s',
                        self._blocking_signal_threshold,
                        ''.join(traceback.format_stack(frame)))

    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 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 run_sync(self, func, timeout=None):
        """Starts the `IOLoop`, runs the given function, and stops the loop.

        The function must return either a yieldable object or
        ``None``. If the function returns a yieldable object, the
        `IOLoop` will run until the yieldable is resolved (and
        `run_sync()` will return the yieldable's result). If it raises
        an exception, the `IOLoop` will stop and the exception will be
        re-raised to the caller.

        The keyword-only argument ``timeout`` may be used to set
        a maximum duration for the function.  If the timeout expires,
        a `tornado.util.TimeoutError` is raised.

        This method is useful in conjunction with `tornado.gen.coroutine`
        to allow asynchronous calls in a ``main()`` function::

            @gen.coroutine
            def main():
                # do stuff...

            if __name__ == '__main__':
                IOLoop.current().run_sync(main)

        .. versionchanged:: 4.3
           Returning a non-``None``, non-yieldable value is now an error.

        .. versionchanged:: 5.0
           If a timeout occurs, the ``func`` coroutine will be cancelled.
        """
        future_cell = [None]

        def run():
            try:
                result = func()
                if result is not None:
                    from tornado.gen import convert_yielded
                    result = convert_yielded(result)
            except Exception:
                future_cell[0] = Future()
                future_set_exc_info(future_cell[0], sys.exc_info())
            else:
                if is_future(result):
                    future_cell[0] = result
                else:
                    future_cell[0] = Future()
                    future_cell[0].set_result(result)
            self.add_future(future_cell[0], lambda future: self.stop())
        self.add_callback(run)
        if timeout is not None:
            def timeout_callback():
                # If we can cancel the future, do so and wait on it. If not,
                # Just stop the loop and return with the task still pending.
                # (If we neither cancel nor wait for the task, a warning
                # will be logged).
                if not future_cell[0].cancel():
                    self.stop()
            timeout_handle = self.add_timeout(self.time() + timeout, timeout_callback)
        self.start()
        if timeout is not None:
            self.remove_timeout(timeout_handle)
        if future_cell[0].cancelled() or not future_cell[0].done():
            raise TimeoutError('Operation timed out after %s seconds' % timeout)
        return future_cell[0].result()

    def time(self):
        """Returns the current time according to the `IOLoop`'s clock.

        The return value is a floating-point number relative to an
        unspecified time in the past.

        By default, the `IOLoop`'s time function is `time.time`.  However,
        it may be configured to use e.g. `time.monotonic` instead.
        Calls to `add_timeout` that pass a number instead of a
        `datetime.timedelta` should use this function to compute the
        appropriate time, so they can work no matter what time function
        is chosen.
        """
        return time.time()

    def add_timeout(self, deadline, callback, *args, **kwargs):
        """Runs the ``callback`` at the time ``deadline`` from the I/O loop.

        Returns an opaque handle that may be passed to
        `remove_timeout` to cancel.

        ``deadline`` may be a number denoting a time (on the same
        scale as `IOLoop.time`, normally `time.time`), or a
        `datetime.timedelta` object for a deadline relative to the
        current time.  Since Tornado 4.0, `call_later` is a more
        convenient alternative for the relative case since it does not
        require a timedelta object.

        Note that it is not safe to call `add_timeout` from other threads.
        Instead, you must use `add_callback` to transfer control to the
        `IOLoop`'s thread, and then call `add_timeout` from there.

        Subclasses of IOLoop must implement either `add_timeout` or
        `call_at`; the default implementations of each will call
        the other.  `call_at` is usually easier to implement, but
        subclasses that wish to maintain compatibility with Tornado
        versions prior to 4.0 must use `add_timeout` instead.

        .. versionchanged:: 4.0
           Now passes through ``*args`` and ``**kwargs`` to the callback.
        """
        if isinstance(deadline, numbers.Real):
            return self.call_at(deadline, callback, *args, **kwargs)
        elif isinstance(deadline, datetime.timedelta):
            return self.call_at(self.time() + timedelta_to_seconds(deadline),
                                callback, *args, **kwargs)
        else:
            raise TypeError("Unsupported deadline %r" % deadline)

    def call_later(self, delay, callback, *args, **kwargs):
        """Runs the ``callback`` after ``delay`` seconds have passed.

        Returns an opaque handle that may be passed to `remove_timeout`
        to cancel.  Note that unlike the `asyncio` method of the same
        name, the returned object does not have a ``cancel()`` method.

        See `add_timeout` for comments on thread-safety and subclassing.

        .. versionadded:: 4.0
        """
        return self.call_at(self.time() + delay, callback, *args, **kwargs)

    def call_at(self, when, callback, *args, **kwargs):
        """Runs the ``callback`` at the absolute time designated by ``when``.

        ``when`` must be a number using the same reference point as
        `IOLoop.time`.

        Returns an opaque handle that may be passed to `remove_timeout`
        to cancel.  Note that unlike the `asyncio` method of the same
        name, the returned object does not have a ``cancel()`` method.

        See `add_timeout` for comments on thread-safety and subclassing.

        .. versionadded:: 4.0
        """
        return self.add_timeout(when, callback, *args, **kwargs)

    def remove_timeout(self, timeout):
        """Cancels a pending timeout.

        The argument is a handle as returned by `add_timeout`.  It is
        safe to call `remove_timeout` even if the callback has already
        been run.
        """
        raise NotImplementedError()

    def add_callback(self, callback, *args, **kwargs):
        """Calls the given callback on the next I/O loop iteration.

        It is safe to call this method from any thread at any time,
        except from a signal handler.  Note that this is the **only**
        method in `IOLoop` that makes this thread-safety guarantee; all
        other interaction with the `IOLoop` must be done from that
        `IOLoop`'s thread.  `add_callback()` may be used to transfer
        control from other threads to the `IOLoop`'s thread.

        To add a callback from a signal handler, see
        `add_callback_from_signal`.
        """
        raise NotImplementedError()

    def add_callback_from_signal(self, callback, *args, **kwargs):
        """Calls the given callback on the next I/O loop iteration.

        Safe for use from a Python signal handler; should not be used
        otherwise.

        Callbacks added with this method will be run without any
        `.stack_context`, to avoid picking up the context of the function
        that was interrupted by the signal.
        """
        raise NotImplementedError()

    def spawn_callback(self, callback, *args, **kwargs):
        """Calls the given callback on the next IOLoop iteration.

        Unlike all other callback-related methods on IOLoop,
        ``spawn_callback`` does not associate the callback with its caller's
        ``stack_context``, so it is suitable for fire-and-forget callbacks
        that should not interfere with the caller.

        .. versionadded:: 4.0
        """
        with stack_context.NullContext():
            self.add_callback(callback, *args, **kwargs)

    def add_future(self, future, callback):
        """Schedules a callback on the ``IOLoop`` when the given
        `.Future` is finished.

        The callback is invoked with one argument, the
        `.Future`.
        """
        assert is_future(future)
        callback = stack_context.wrap(callback)
        future_add_done_callback(
            future, lambda future: self.add_callback(callback, future))

    def run_in_executor(self, executor, func, *args):
        """Runs a function in a ``concurrent.futures.Executor``. If
        ``executor`` is ``None``, the IO loop's default executor will be used.

        Use `functools.partial` to pass keyword arguments to ``func``.

        .. versionadded:: 5.0
        """
        if ThreadPoolExecutor is None:
            raise RuntimeError(
                "concurrent.futures is required to use IOLoop.run_in_executor")

        if executor is None:
            if not hasattr(self, '_executor'):
                from tornado.process import cpu_count
                self._executor = ThreadPoolExecutor(max_workers=(cpu_count() * 5))
            executor = self._executor
        c_future = executor.submit(func, *args)
        # Concurrent Futures are not usable with await. Wrap this in a
        # Tornado Future instead, using self.add_future for thread-safety.
        t_future = Future()
        self.add_future(c_future, lambda f: chain_future(f, t_future))
        return t_future

    def set_default_executor(self, executor):
        """Sets the default executor to use with :meth:`run_in_executor`.

        .. versionadded:: 5.0
        """
        self._executor = executor

    def _run_callback(self, callback):
        """Runs a callback with error handling.

        For use in subclasses.
        """
        try:
            ret = callback()
            if ret is not None:
                from tornado import gen
                # Functions that return Futures typically swallow all
                # exceptions and store them in the Future.  If a Future
                # makes it out to the IOLoop, ensure its exception (if any)
                # gets logged too.
                try:
                    ret = gen.convert_yielded(ret)
                except gen.BadYieldError:
                    # It's not unusual for add_callback to be used with
                    # methods returning a non-None and non-yieldable
                    # result, which should just be ignored.
                    pass
                else:
                    self.add_future(ret, self._discard_future_result)
        except Exception:
            self.handle_callback_exception(callback)

    def _discard_future_result(self, future):
        """Avoid unhandled-exception warnings from spawned coroutines."""
        future.result()

    def handle_callback_exception(self, callback):
        """This method is called whenever a callback run by the `IOLoop`
        throws an exception.

        By default simply logs the exception as an error.  Subclasses
        may override this method to customize reporting of exceptions.

        The exception itself is not passed explicitly, but is available
        in `sys.exc_info`.
        """
        app_log.error("Exception in callback %r", callback, exc_info=True)

    def split_fd(self, fd):
        """Returns an (fd, obj) pair from an ``fd`` parameter.

        We accept both raw file descriptors and file-like objects as
        input to `add_handler` and related methods.  When a file-like
        object is passed, we must retain the object itself so we can
        close it correctly when the `IOLoop` shuts down, but the
        poller interfaces favor file descriptors (they will accept
        file-like objects and call ``fileno()`` for you, but they
        always return the descriptor itself).

        This method is provided for use by `IOLoop` subclasses and should
        not generally be used by application code.

        .. versionadded:: 4.0
        """
        try:
            return fd.fileno(), fd
        except AttributeError:
            return fd, fd

    def close_fd(self, fd):
        """Utility method to close an ``fd``.

        If ``fd`` is a file-like object, we close it directly; otherwise
        we use `os.close`.

        This method is provided for use by `IOLoop` subclasses (in
        implementations of ``IOLoop.close(all_fds=True)`` and should
        not generally be used by application code.

        .. versionadded:: 4.0
        """
        try:
            try:
                fd.close()
            except AttributeError:
                os.close(fd)
        except OSError:
            pass


class PollIOLoop(IOLoop):
    """Base class for IOLoops built around a select-like function.

    For concrete implementations, see `tornado.platform.epoll.EPollIOLoop`
    (Linux), `tornado.platform.kqueue.KQueueIOLoop` (BSD and Mac), or
    `tornado.platform.select.SelectIOLoop` (all platforms).
    """
    def initialize(self, impl, time_func=None, **kwargs):
        super(PollIOLoop, self).initialize(**kwargs)
        self._impl = impl
        if hasattr(self._impl, 'fileno'):
            set_close_exec(self._impl.fileno())
        self.time_func = time_func or time.time
        self._handlers = {}
        self._events = {}
        self._callbacks = collections.deque()
        self._timeouts = []
        self._cancellations = 0
        self._running = False
        self._stopped = False
        self._closing = False
        self._thread_ident = None
        self._pid = os.getpid()
        self._blocking_signal_threshold = None
        self._timeout_counter = itertools.count()

        # Create a pipe that we send bogus data to when we want to wake
        # the I/O loop when it is idle
        self._waker = Waker()
        self.add_handler(self._waker.fileno(),
                         lambda fd, events: self._waker.consume(),
                         self.READ)

    @classmethod
    def configurable_base(cls):
        return PollIOLoop

    @classmethod
    def configurable_default(cls):
        if hasattr(select, "epoll"):
            from tornado.platform.epoll import EPollIOLoop
            return EPollIOLoop
        if hasattr(select, "kqueue"):
            # Python 2.6+ on BSD or Mac
            from tornado.platform.kqueue import KQueueIOLoop
            return KQueueIOLoop
        from tornado.platform.select import SelectIOLoop
        return SelectIOLoop

    def close(self, all_fds=False):
        self._closing = True
        self.remove_handler(self._waker.fileno())
        if all_fds:
            for fd, handler in list(self._handlers.values()):
                self.close_fd(fd)
        self._waker.close()
        self._impl.close()
        self._callbacks = None
        self._timeouts = None
        if hasattr(self, '_executor'):
            self._executor.shutdown()

    def add_handler(self, fd, handler, events):
        fd, obj = self.split_fd(fd)
        self._handlers[fd] = (obj, stack_context.wrap(handler))
        self._impl.register(fd, events | self.ERROR)

    def update_handler(self, fd, events):
        fd, obj = self.split_fd(fd)
        self._impl.modify(fd, events | self.ERROR)

    def remove_handler(self, fd):
        fd, obj = self.split_fd(fd)
        self._handlers.pop(fd, None)
        self._events.pop(fd, None)
        try:
            self._impl.unregister(fd)
        except Exception:
            gen_log.debug("Error deleting fd from IOLoop", exc_info=True)

    def set_blocking_signal_threshold(self, seconds, action):
        if not hasattr(signal, "setitimer"):
            gen_log.error("set_blocking_signal_threshold requires a signal module "
                          "with the setitimer method")
            return
        self._blocking_signal_threshold = seconds
        if seconds is not None:
            signal.signal(signal.SIGALRM,
                          action if action is not None else signal.SIG_DFL)

    def start(self):
        if self._running:
            raise RuntimeError("IOLoop is already running")
        if os.getpid() != self._pid:
            raise RuntimeError("Cannot share PollIOLoops across processes")
        self._setup_logging()
        if self._stopped:
            self._stopped = False
            return
        old_current = IOLoop.current(instance=False)
        if old_current is not self:
            self.make_current()
        self._thread_ident = thread.get_ident()
        self._running = True

        # signal.set_wakeup_fd closes a race condition in event loops:
        # a signal may arrive at the beginning of select/poll/etc
        # before it goes into its interruptible sleep, so the signal
        # will be consumed without waking the select.  The solution is
        # for the (C, synchronous) signal handler to write to a pipe,
        # which will then be seen by select.
        #
        # In python's signal handling semantics, this only matters on the
        # main thread (fortunately, set_wakeup_fd only works on the main
        # thread and will raise a ValueError otherwise).
        #
        # If someone has already set a wakeup fd, we don't want to
        # disturb it.  This is an issue for twisted, which does its
        # SIGCHLD processing in response to its own wakeup fd being
        # written to.  As long as the wakeup fd is registered on the IOLoop,
        # the loop will still wake up and everything should work.
        old_wakeup_fd = None
        if hasattr(signal, 'set_wakeup_fd') and os.name == 'posix':
            # requires python 2.6+, unix.  set_wakeup_fd exists but crashes
            # the python process on windows.
            try:
                old_wakeup_fd = signal.set_wakeup_fd(self._waker.write_fileno())
                if old_wakeup_fd != -1:
                    # Already set, restore previous value.  This is a little racy,
                    # but there's no clean get_wakeup_fd and in real use the
                    # IOLoop is just started once at the beginning.
                    signal.set_wakeup_fd(old_wakeup_fd)
                    old_wakeup_fd = None
            except ValueError:
                # Non-main thread, or the previous value of wakeup_fd
                # is no longer valid.
                old_wakeup_fd = None

        try:
            while True:
                # Prevent IO event starvation by delaying new callbacks
                # to the next iteration of the event loop.
                ncallbacks = len(self._callbacks)

                # Add any timeouts that have come due to the callback list.
                # Do not run anything until we have determined which ones
                # are ready, so timeouts that call add_timeout cannot
                # schedule anything in this iteration.
                due_timeouts = []
                if self._timeouts:
                    now = self.time()
                    while self._timeouts:
                        if self._timeouts[0].callback is None:
                            # The timeout was cancelled.  Note that the
                            # cancellation check is repeated below for timeouts
                            # that are cancelled by another timeout or callback.
                            heapq.heappop(self._timeouts)
                            self._cancellations -= 1
                        elif self._timeouts[0].deadline <= now:
                            due_timeouts.append(heapq.heappop(self._timeouts))
                        else:
                            break
                    if (self._cancellations > 512 and
                            self._cancellations > (len(self._timeouts) >> 1)):
                        # Clean up the timeout queue when it gets large and it's
                        # more than half cancellations.
                        self._cancellations = 0
                        self._timeouts = [x for x in self._timeouts
                                          if x.callback is not None]
                        heapq.heapify(self._timeouts)

                for i in range(ncallbacks):
                    self._run_callback(self._callbacks.popleft())
                for timeout in due_timeouts:
                    if timeout.callback is not None:
                        self._run_callback(timeout.callback)
                # Closures may be holding on to a lot of memory, so allow
                # them to be freed before we go into our poll wait.
                due_timeouts = timeout = None

                if self._callbacks:
                    # If any callbacks or timeouts called add_callback,
                    # we don't want to wait in poll() before we run them.
                    poll_timeout = 0.0
                elif self._timeouts:
                    # If there are any timeouts, schedule the first one.
                    # Use self.time() instead of 'now' to account for time
                    # spent running callbacks.
                    poll_timeout = self._timeouts[0].deadline - self.time()
                    poll_timeout = max(0, min(poll_timeout, _POLL_TIMEOUT))
                else:
                    # No timeouts and no callbacks, so use the default.
                    poll_timeout = _POLL_TIMEOUT

                if not self._running:
                    break

                if self._blocking_signal_threshold is not None:
                    # clear alarm so it doesn't fire while poll is waiting for
                    # events.
                    signal.setitimer(signal.ITIMER_REAL, 0, 0)

                try:
                    event_pairs = self._impl.poll(poll_timeout)
                except Exception as e:
                    # Depending on python version and IOLoop implementation,
                    # different exception types may be thrown and there are
                    # two ways EINTR might be signaled:
                    # * e.errno == errno.EINTR
                    # * e.args is like (errno.EINTR, 'Interrupted system call')
                    if errno_from_exception(e) == errno.EINTR:
                        continue
                    else:
                        raise

                if self._blocking_signal_threshold is not None:
                    signal.setitimer(signal.ITIMER_REAL,
                                     self._blocking_signal_threshold, 0)

                # Pop one fd at a time from the set of pending fds and run
                # its handler. Since that handler may perform actions on
                # other file descriptors, there may be reentrant calls to
                # this IOLoop that modify self._events
                self._events.update(event_pairs)
                while self._events:
                    fd, events = self._events.popitem()
                    try:
                        fd_obj, handler_func = self._handlers[fd]
                        handler_func(fd_obj, events)
                    except (OSError, IOError) as e:
                        if errno_from_exception(e) == errno.EPIPE:
                            # Happens when the client closes the connection
                            pass
                        else:
                            self.handle_callback_exception(self._handlers.get(fd))
                    except Exception:
                        self.handle_callback_exception(self._handlers.get(fd))
                fd_obj = handler_func = None

        finally:
            # reset the stopped flag so another start/stop pair can be issued
            self._stopped = False
            if self._blocking_signal_threshold is not None:
                signal.setitimer(signal.ITIMER_REAL, 0, 0)
            if old_current is None:
                IOLoop.clear_current()
            elif old_current is not self:
                old_current.make_current()
            if old_wakeup_fd is not None:
                signal.set_wakeup_fd(old_wakeup_fd)

    def stop(self):
        self._running = False
        self._stopped = True
        self._waker.wake()

    def time(self):
        return self.time_func()

    def call_at(self, deadline, callback, *args, **kwargs):
        timeout = _Timeout(
            deadline,
            functools.partial(stack_context.wrap(callback), *args, **kwargs),
            self)
        heapq.heappush(self._timeouts, timeout)
        return timeout

    def remove_timeout(self, timeout):
        # Removing from a heap is complicated, so just leave the defunct
        # timeout object in the queue (see discussion in
        # http://docs.python.org/library/heapq.html).
        # If this turns out to be a problem, we could add a garbage
        # collection pass whenever there are too many dead timeouts.
        timeout.callback = None
        self._cancellations += 1

    def add_callback(self, callback, *args, **kwargs):
        if self._closing:
            return
        # Blindly insert into self._callbacks. This is safe even
        # from signal handlers because deque.append is atomic.
        self._callbacks.append(functools.partial(
            stack_context.wrap(callback), *args, **kwargs))
        if thread.get_ident() != self._thread_ident:
            # This will write one byte but Waker.consume() reads many
            # at once, so it's ok to write even when not strictly
            # necessary.
            self._waker.wake()
        else:
            # If we're on the IOLoop's thread, we don't need to wake anyone.
            pass

    def add_callback_from_signal(self, callback, *args, **kwargs):
        with stack_context.NullContext():
            self.add_callback(callback, *args, **kwargs)


class _Timeout(object):
    """An IOLoop timeout, a UNIX timestamp and a callback"""

    # Reduce memory overhead when there are lots of pending callbacks
    __slots__ = ['deadline', 'callback', 'tdeadline']

    def __init__(self, deadline, callback, io_loop):
        if not isinstance(deadline, numbers.Real):
            raise TypeError("Unsupported deadline %r" % deadline)
        self.deadline = deadline
        self.callback = callback
        self.tdeadline = (deadline, next(io_loop._timeout_counter))

    # Comparison methods to sort by deadline, with object id as a tiebreaker
    # to guarantee a consistent ordering.  The heapq module uses __le__
    # in python2.5, and __lt__ in 2.6+ (sort() and most other comparisons
    # use __lt__).
    def __lt__(self, other):
        return self.tdeadline < other.tdeadline

    def __le__(self, other):
        return self.tdeadline <= other.tdeadline


class PeriodicCallback(object):
    """Schedules the given callback to be called periodically.

    The callback is called every ``callback_time`` milliseconds.
    Note that the timeout is given in milliseconds, while most other
    time-related functions in Tornado use seconds.

    If the callback runs for longer than ``callback_time`` milliseconds,
    subsequent invocations will be skipped to get back on schedule.

    `start` must be called after the `PeriodicCallback` is created.

    .. versionchanged:: 5.0
       The ``io_loop`` argument (deprecated since version 4.1) has been removed.
    """
    def __init__(self, callback, callback_time):
        self.callback = callback
        if callback_time <= 0:
            raise ValueError("Periodic callback must have a positive callback_time")
        self.callback_time = callback_time
        self._running = False
        self._timeout = None

    def start(self):
        """Starts the timer."""
        # Looking up the IOLoop here allows to first instantiate the
        # PeriodicCallback in another thread, then start it using
        # IOLoop.add_callback().
        self.io_loop = IOLoop.current()
        self._running = True
        self._next_timeout = self.io_loop.time()
        self._schedule_next()

    def stop(self):
        """Stops the timer."""
        self._running = False
        if self._timeout is not None:
            self.io_loop.remove_timeout(self._timeout)
            self._timeout = None

    def is_running(self):
        """Return True if this `.PeriodicCallback` has been started.

        .. versionadded:: 4.1
        """
        return self._running

    def _run(self):
        if not self._running:
            return
        try:
            return self.callback()
        except Exception:
            self.io_loop.handle_callback_exception(self.callback)
        finally:
            self._schedule_next()

    def _schedule_next(self):
        if self._running:
            current_time = self.io_loop.time()

            if self._next_timeout <= current_time:
                callback_time_sec = self.callback_time / 1000.0
                self._next_timeout += (math.floor((current_time - self._next_timeout) /
                                                  callback_time_sec) + 1) * callback_time_sec

            self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run)

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
[ISSUE]
**Title:** `PeriodicCallback` Missing `_update_next` Method Causing Test Failures

**Description:**
When running tests designed to verify the mathematical calculations of `PeriodicCallback`, an `AttributeError` is raised because the `_update_next` method does not exist in the `PeriodicCallback` class. This prevents the tests from executing the intended logic separately from the IOLoop configuration.

**Example Code:**
```python
class TestPeriodicCallbackMath(unittest.TestCase):
    def simulate_calls(self, pc, durations):
        calls = []
        now = 1000
        pc._next_timeout = now
        for d in durations:
            pc._update_next(now)
            calls.append(pc._next_timeout)
            now = pc._next_timeout + d
        return calls

    def test_basic(self):
        pc = PeriodicCallback(None, 10000)
        self.simulate_calls(pc, [0] * 5)
```

**Expected Behavior:**
The `PeriodicCallback` class should include the `_update_next` method, allowing the mathematical scheduling logic to be tested independently. This method should correctly update the next timeout based on the current time and callback interval.

**Actual Behavior:**
Running the tests results in the following error:
```
AttributeError: 'PeriodicCallback' object has no attribute '_update_next'
```
This error prevents the math-related tests from executing, hindering the ability to verify the correctness of the periodic callback scheduling.

[/ISSUE]
{
    "TestIOLoop.test_add_callback_from_signal": "PASSED",
    "TestIOLoop.test_add_callback_from_signal_other_thread": "PASSED",
    "TestIOLoop.test_add_callback_return_sequence": "PASSED",
    "TestIOLoop.test_add_callback_wakeup": "PASSED",
    "TestIOLoop.test_add_callback_wakeup_other_thread": "PASSED",
    "TestIOLoop.test_add_callback_while_closing": "PASSED",
    "TestIOLoop.test_add_timeout_return": "PASSED",
    "TestIOLoop.test_add_timeout_timedelta": "PASSED",
    "TestIOLoop.test_call_at_return": "PASSED",
    "TestIOLoop.test_call_later_return": "PASSED",
    "TestIOLoop.test_close_file_object": "PASSED",
    "TestIOLoop.test_exception_logging": "PASSED",
    "TestIOLoop.test_exception_logging_future": "PASSED",
    "TestIOLoop.test_exception_logging_native_coro": "PASSED",
    "TestIOLoop.test_handle_callback_exception": "PASSED",
    "TestIOLoop.test_handler_callback_file_object": "PASSED",
    "TestIOLoop.test_mixed_fd_fileobj": "PASSED",
    "TestIOLoop.test_multiple_add": "PASSED",
    "TestIOLoop.test_read_while_writeable": "PASSED",
    "TestIOLoop.test_reentrant": "PASSED",
    "TestIOLoop.test_remove_handler_from_handler": "PASSED",
    "TestIOLoop.test_remove_timeout_after_fire": "PASSED",
    "TestIOLoop.test_remove_timeout_cleanup": "PASSED",
    "TestIOLoop.test_remove_timeout_from_timeout": "PASSED",
    "TestIOLoop.test_remove_without_add": "PASSED",
    "TestIOLoop.test_spawn_callback": "PASSED",
    "TestIOLoop.test_timeout_with_arguments": "PASSED",
    "TestIOLoopAddCallback.test_pre_wrap": "PASSED",
    "TestIOLoopAddCallback.test_pre_wrap_with_args": "PASSED",
    "TestIOLoopAddCallbackFromSignal.test_pre_wrap": "PASSED",
    "TestIOLoopAddCallbackFromSignal.test_pre_wrap_with_args": "PASSED",
    "TestIOLoopConfiguration.test_asyncio": "PASSED",
    "TestIOLoopConfiguration.test_asyncio_main": "PASSED",
    "TestIOLoopConfiguration.test_default": "PASSED",
    "TestIOLoopCurrent.test_default_current": "PASSED",
    "TestIOLoopCurrent.test_force_current": "PASSED",
    "TestIOLoopCurrent.test_non_current": "PASSED",
    "TestIOLoopCurrentAsync.test_clear_without_current": "PASSED",
    "TestIOLoopFutures.test_add_future_stack_context": "PASSED",
    "TestIOLoopFutures.test_add_future_threads": "PASSED",
    "TestIOLoopFutures.test_run_in_executor_gen": "PASSED",
    "TestIOLoopFutures.test_run_in_executor_native": "PASSED",
    "TestIOLoopFutures.test_set_default_executor": "PASSED",
    "TestIOLoopRunSync.test_async_exception": "PASSED",
    "TestIOLoopRunSync.test_async_result": "PASSED",
    "TestIOLoopRunSync.test_current": "PASSED",
    "TestIOLoopRunSync.test_native_coroutine": "PASSED",
    "TestIOLoopRunSync.test_sync_exception": "PASSED",
    "TestIOLoopRunSync.test_sync_result": "PASSED",
    "TestIOLoopRunSync.test_timeout": "PASSED",
    "TestPeriodicCallbackMath.test_basic": "PASSED",
    "TestPeriodicCallbackMath.test_overrun": "PASSED"
}
diff --git a/tornado/ioloop.py b/tornado/ioloop.py
index f6ec177b..45d2d223 100644
--- a/tornado/ioloop.py
+++ b/tornado/ioloop.py
@@ -1213,11 +1213,11 @@ class PeriodicCallback(object):
 
     def _schedule_next(self):
         if self._running:
-            current_time = self.io_loop.time()
-
-            if self._next_timeout <= current_time:
-                callback_time_sec = self.callback_time / 1000.0
-                self._next_timeout += (math.floor((current_time - self._next_timeout) /
-                                                  callback_time_sec) + 1) * callback_time_sec
-
+            self._update_next(self.io_loop.time())
             self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run)
+
+    def _update_next(self, current_time):
+        if self._next_timeout <= current_time:
+            callback_time_sec = self.callback_time / 1000.0
+            self._next_timeout += (math.floor((current_time - self._next_timeout) /
+                                              callback_time_sec) + 1) * callback_time_sec

{"tornado/ioloop.py": "#\n# Copyright 2009 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"An I/O event loop for non-blocking sockets.\n\nOn Python 3, `.IOLoop` is a wrapper around the `asyncio` event loop.\n\nTypical applications will use a single `IOLoop` object, accessed via\n`IOLoop.current` class method. The `IOLoop.start` method (or\nequivalently, `asyncio.AbstractEventLoop.run_forever`) should usually\nbe called at the end of the ``main()`` function. Atypical applications\nmay use more than one `IOLoop`, such as one `IOLoop` per thread, or\nper `unittest` case.\n\nIn addition to I/O events, the `IOLoop` can also schedule time-based\nevents. `IOLoop.add_timeout` is a non-blocking alternative to\n`time.sleep`.\n\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nimport collections\nimport datetime\nimport errno\nimport functools\nimport heapq\nimport itertools\nimport logging\nimport numbers\nimport os\nimport select\nimport sys\nimport threading\nimport time\nimport traceback\nimport math\n\nfrom tornado.concurrent import Future, is_future, chain_future, future_set_exc_info, future_add_done_callback  # noqa: E501\nfrom tornado.log import app_log, gen_log\nfrom tornado.platform.auto import set_close_exec, Waker\nfrom tornado import stack_context\nfrom tornado.util import (\n    PY3, Configurable, errno_from_exception, timedelta_to_seconds,\n    TimeoutError, unicode_type, import_object,\n)\n\ntry:\n    import signal\nexcept ImportError:\n    signal = None\n\ntry:\n    from concurrent.futures import ThreadPoolExecutor\nexcept ImportError:\n    ThreadPoolExecutor = None\n\nif PY3:\n    import _thread as thread\nelse:\n    import thread\n\ntry:\n    import asyncio\nexcept ImportError:\n    asyncio = None\n\n\n_POLL_TIMEOUT = 3600.0\n\n\nclass IOLoop(Configurable):\n    \"\"\"A level-triggered I/O loop.\n\n    On Python 3, `IOLoop` is a wrapper around the `asyncio` event\n    loop. On Python 2, it uses ``epoll`` (Linux) or ``kqueue`` (BSD\n    and Mac OS X) if they are available, or else we fall back on\n    select(). If you are implementing a system that needs to handle\n    thousands of simultaneous connections, you should use a system\n    that supports either ``epoll`` or ``kqueue``.\n\n    Example usage for a simple TCP server:\n\n    .. testcode::\n\n        import errno\n        import functools\n        import socket\n\n        import tornado.ioloop\n        from tornado import gen\n        from tornado.iostream import IOStream\n\n        @gen.coroutine\n        def handle_connection(connection, address):\n            stream = IOStream(connection)\n            message = yield stream.read_until_close()\n            print(\"message from client:\", message.decode().strip())\n\n        def connection_ready(sock, fd, events):\n            while True:\n                try:\n                    connection, address = sock.accept()\n                except socket.error as e:\n                    if e.args[0] not in (errno.EWOULDBLOCK, errno.EAGAIN):\n                        raise\n                    return\n                connection.setblocking(0)\n                handle_connection(connection, address)\n\n        if __name__ == '__main__':\n            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)\n            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n            sock.setblocking(0)\n            sock.bind((\"\", 8888))\n            sock.listen(128)\n\n            io_loop = tornado.ioloop.IOLoop.current()\n            callback = functools.partial(connection_ready, sock)\n            io_loop.add_handler(sock.fileno(), callback, io_loop.READ)\n            io_loop.start()\n\n    .. testoutput::\n       :hide:\n\n    By default, a newly-constructed `IOLoop` becomes the thread's current\n    `IOLoop`, unless there already is a current `IOLoop`. This behavior\n    can be controlled with the ``make_current`` argument to the `IOLoop`\n    constructor: if ``make_current=True``, the new `IOLoop` will always\n    try to become current and it raises an error if there is already a\n    current instance. If ``make_current=False``, the new `IOLoop` will\n    not try to become current.\n\n    In general, an `IOLoop` cannot survive a fork or be shared across\n    processes in any way. When multiple processes are being used, each\n    process should create its own `IOLoop`, which also implies that\n    any objects which depend on the `IOLoop` (such as\n    `.AsyncHTTPClient`) must also be created in the child processes.\n    As a guideline, anything that starts processes (including the\n    `tornado.process` and `multiprocessing` modules) should do so as\n    early as possible, ideally the first thing the application does\n    after loading its configuration in ``main()``.\n\n    .. versionchanged:: 4.2\n       Added the ``make_current`` keyword argument to the `IOLoop`\n       constructor.\n\n    .. versionchanged:: 5.0\n\n       Uses the `asyncio` event loop by default. The\n       ``IOLoop.configure`` method cannot be used on Python 3 except\n       to redundantly specify the `asyncio` event loop.\n\n    \"\"\"\n    # Constants from the epoll module\n    _EPOLLIN = 0x001\n    _EPOLLPRI = 0x002\n    _EPOLLOUT = 0x004\n    _EPOLLERR = 0x008\n    _EPOLLHUP = 0x010\n    _EPOLLRDHUP = 0x2000\n    _EPOLLONESHOT = (1 << 30)\n    _EPOLLET = (1 << 31)\n\n    # Our events map exactly to the epoll events\n    NONE = 0\n    READ = _EPOLLIN\n    WRITE = _EPOLLOUT\n    ERROR = _EPOLLERR | _EPOLLHUP\n\n    # In Python 2, _current.instance points to the current IOLoop.\n    _current = threading.local()\n\n    # In Python 3, _ioloop_for_asyncio maps from asyncio loops to IOLoops.\n    _ioloop_for_asyncio = dict()\n\n    @classmethod\n    def configure(cls, impl, **kwargs):\n        if asyncio is not None:\n            from tornado.platform.asyncio import BaseAsyncIOLoop\n\n            if isinstance(impl, (str, unicode_type)):\n                impl = import_object(impl)\n            if not issubclass(impl, BaseAsyncIOLoop):\n                raise RuntimeError(\n                    \"only AsyncIOLoop is allowed when asyncio is available\")\n        super(IOLoop, cls).configure(impl, **kwargs)\n\n    @staticmethod\n    def instance():\n        \"\"\"Deprecated alias for `IOLoop.current()`.\n\n        .. versionchanged:: 5.0\n\n           Previously, this method returned a global singleton\n           `IOLoop`, in contrast with the per-thread `IOLoop` returned\n           by `current()`. In nearly all cases the two were the same\n           (when they differed, it was generally used from non-Tornado\n           threads to communicate back to the main thread's `IOLoop`).\n           This distinction is not present in `asyncio`, so in order\n           to facilitate integration with that package `instance()`\n           was changed to be an alias to `current()`. Applications\n           using the cross-thread communications aspect of\n           `instance()` should instead set their own global variable\n           to point to the `IOLoop` they want to use.\n\n        .. deprecated:: 5.0\n        \"\"\"\n        return IOLoop.current()\n\n    def install(self):\n        \"\"\"Deprecated alias for `make_current()`.\n\n        .. versionchanged:: 5.0\n\n           Previously, this method would set this `IOLoop` as the\n           global singleton used by `IOLoop.instance()`. Now that\n           `instance()` is an alias for `current()`, `install()`\n           is an alias for `make_current()`.\n\n        .. deprecated:: 5.0\n        \"\"\"\n        self.make_current()\n\n    @staticmethod\n    def clear_instance():\n        \"\"\"Deprecated alias for `clear_current()`.\n\n        .. versionchanged:: 5.0\n\n           Previously, this method would clear the `IOLoop` used as\n           the global singleton by `IOLoop.instance()`. Now that\n           `instance()` is an alias for `current()`,\n           `clear_instance()` is an alias for `clear_current()`.\n\n        .. deprecated:: 5.0\n\n        \"\"\"\n        IOLoop.clear_current()\n\n    @staticmethod\n    def current(instance=True):\n        \"\"\"Returns the current thread's `IOLoop`.\n\n        If an `IOLoop` is currently running or has been marked as\n        current by `make_current`, returns that instance.  If there is\n        no current `IOLoop` and ``instance`` is true, creates one.\n\n        .. versionchanged:: 4.1\n           Added ``instance`` argument to control the fallback to\n           `IOLoop.instance()`.\n        .. versionchanged:: 5.0\n           On Python 3, control of the current `IOLoop` is delegated\n           to `asyncio`, with this and other methods as pass-through accessors.\n           The ``instance`` argument now controls whether an `IOLoop`\n           is created automatically when there is none, instead of\n           whether we fall back to `IOLoop.instance()` (which is now\n           an alias for this method). ``instance=False`` is deprecated,\n           since even if we do not create an `IOLoop`, this method\n           may initialize the asyncio loop.\n        \"\"\"\n        if asyncio is None:\n            current = getattr(IOLoop._current, \"instance\", None)\n            if current is None and instance:\n                current = IOLoop()\n                if IOLoop._current.instance is not current:\n                    raise RuntimeError(\"new IOLoop did not become current\")\n        else:\n            try:\n                loop = asyncio.get_event_loop()\n            except (RuntimeError, AssertionError):\n                if not instance:\n                    return None\n                raise\n            try:\n                return IOLoop._ioloop_for_asyncio[loop]\n            except KeyError:\n                if instance:\n                    from tornado.platform.asyncio import AsyncIOMainLoop\n                    current = AsyncIOMainLoop(make_current=True)\n                else:\n                    current = None\n        return current\n\n    def make_current(self):\n        \"\"\"Makes this the `IOLoop` for the current thread.\n\n        An `IOLoop` automatically becomes current for its thread\n        when it is started, but it is sometimes useful to call\n        `make_current` explicitly before starting the `IOLoop`,\n        so that code run at startup time can find the right\n        instance.\n\n        .. versionchanged:: 4.1\n           An `IOLoop` created while there is no current `IOLoop`\n           will automatically become current.\n\n        .. versionchanged:: 5.0\n           This method also sets the current `asyncio` event loop.\n        \"\"\"\n        # The asyncio event loops override this method.\n        assert asyncio is None\n        old = getattr(IOLoop._current, \"instance\", None)\n        if old is not None:\n            old.clear_current()\n        IOLoop._current.instance = self\n\n    @staticmethod\n    def clear_current():\n        \"\"\"Clears the `IOLoop` for the current thread.\n\n        Intended primarily for use by test frameworks in between tests.\n\n        .. versionchanged:: 5.0\n           This method also clears the current `asyncio` event loop.\n        \"\"\"\n        old = IOLoop.current(instance=False)\n        if old is not None:\n            old._clear_current_hook()\n        if asyncio is None:\n            IOLoop._current.instance = None\n\n    def _clear_current_hook(self):\n        \"\"\"Instance method called when an IOLoop ceases to be current.\n\n        May be overridden by subclasses as a counterpart to make_current.\n        \"\"\"\n        pass\n\n    @classmethod\n    def configurable_base(cls):\n        return IOLoop\n\n    @classmethod\n    def configurable_default(cls):\n        if asyncio is not None:\n            from tornado.platform.asyncio import AsyncIOLoop\n            return AsyncIOLoop\n        return PollIOLoop\n\n    def initialize(self, make_current=None):\n        if make_current is None:\n            if IOLoop.current(instance=False) is None:\n                self.make_current()\n        elif make_current:\n            current = IOLoop.current(instance=False)\n            # AsyncIO loops can already be current by this point.\n            if current is not None and current is not self:\n                raise RuntimeError(\"current IOLoop already exists\")\n            self.make_current()\n\n    def close(self, all_fds=False):\n        \"\"\"Closes the `IOLoop`, freeing any resources used.\n\n        If ``all_fds`` is true, all file descriptors registered on the\n        IOLoop will be closed (not just the ones created by the\n        `IOLoop` itself).\n\n        Many applications will only use a single `IOLoop` that runs for the\n        entire lifetime of the process.  In that case closing the `IOLoop`\n        is not necessary since everything will be cleaned up when the\n        process exits.  `IOLoop.close` is provided mainly for scenarios\n        such as unit tests, which create and destroy a large number of\n        ``IOLoops``.\n\n        An `IOLoop` must be completely stopped before it can be closed.  This\n        means that `IOLoop.stop()` must be called *and* `IOLoop.start()` must\n        be allowed to return before attempting to call `IOLoop.close()`.\n        Therefore the call to `close` will usually appear just after\n        the call to `start` rather than near the call to `stop`.\n\n        .. versionchanged:: 3.1\n           If the `IOLoop` implementation supports non-integer objects\n           for \"file descriptors\", those objects will have their\n           ``close`` method when ``all_fds`` is true.\n        \"\"\"\n        raise NotImplementedError()\n\n    def add_handler(self, fd, handler, events):\n        \"\"\"Registers the given handler to receive the given events for ``fd``.\n\n        The ``fd`` argument may either be an integer file descriptor or\n        a file-like object with a ``fileno()`` method (and optionally a\n        ``close()`` method, which may be called when the `IOLoop` is shut\n        down).\n\n        The ``events`` argument is a bitwise or of the constants\n        ``IOLoop.READ``, ``IOLoop.WRITE``, and ``IOLoop.ERROR``.\n\n        When an event occurs, ``handler(fd, events)`` will be run.\n\n        .. versionchanged:: 4.0\n           Added the ability to pass file-like objects in addition to\n           raw file descriptors.\n        \"\"\"\n        raise NotImplementedError()\n\n    def update_handler(self, fd, events):\n        \"\"\"Changes the events we listen for ``fd``.\n\n        .. versionchanged:: 4.0\n           Added the ability to pass file-like objects in addition to\n           raw file descriptors.\n        \"\"\"\n        raise NotImplementedError()\n\n    def remove_handler(self, fd):\n        \"\"\"Stop listening for events on ``fd``.\n\n        .. versionchanged:: 4.0\n           Added the ability to pass file-like objects in addition to\n           raw file descriptors.\n        \"\"\"\n        raise NotImplementedError()\n\n    def set_blocking_signal_threshold(self, seconds, action):\n        \"\"\"Sends a signal if the `IOLoop` is blocked for more than\n        ``s`` seconds.\n\n        Pass ``seconds=None`` to disable.  Requires Python 2.6 on a unixy\n        platform.\n\n        The action parameter is a Python signal handler.  Read the\n        documentation for the `signal` module for more information.\n        If ``action`` is None, the process will be killed if it is\n        blocked for too long.\n\n        .. deprecated:: 5.0\n\n           Not implemented on the `asyncio` event loop. Use the environment\n           variable ``PYTHONASYNCIODEBUG=1`` instead.\n        \"\"\"\n        raise NotImplementedError()\n\n    def set_blocking_log_threshold(self, seconds):\n        \"\"\"Logs a stack trace if the `IOLoop` is blocked for more than\n        ``s`` seconds.\n\n        Equivalent to ``set_blocking_signal_threshold(seconds,\n        self.log_stack)``\n\n        .. deprecated:: 5.0\n\n           Not implemented on the `asyncio` event loop. Use the environment\n           variable ``PYTHONASYNCIODEBUG=1`` instead.\n        \"\"\"\n        self.set_blocking_signal_threshold(seconds, self.log_stack)\n\n    def log_stack(self, signal, frame):\n        \"\"\"Signal handler to log the stack trace of the current thread.\n\n        For use with `set_blocking_signal_threshold`.\n        \"\"\"\n        gen_log.warning('IOLoop blocked for %f seconds in\\n%s',\n                        self._blocking_signal_threshold,\n                        ''.join(traceback.format_stack(frame)))\n\n    def start(self):\n        \"\"\"Starts the I/O loop.\n\n        The loop will run until one of the callbacks calls `stop()`, which\n        will make the loop stop after the current event iteration completes.\n        \"\"\"\n        raise NotImplementedError()\n\n    def _setup_logging(self):\n        \"\"\"The IOLoop catches and logs exceptions, so it's\n        important that log output be visible.  However, python's\n        default behavior for non-root loggers (prior to python\n        3.2) is to print an unhelpful \"no handlers could be\n        found\" message rather than the actual log entry, so we\n        must explicitly configure logging if we've made it this\n        far without anything.\n\n        This method should be called from start() in subclasses.\n        \"\"\"\n        if not any([logging.getLogger().handlers,\n                    logging.getLogger('tornado').handlers,\n                    logging.getLogger('tornado.application').handlers]):\n            logging.basicConfig()\n\n    def stop(self):\n        \"\"\"Stop the I/O loop.\n\n        If the event loop is not currently running, the next call to `start()`\n        will return immediately.\n\n        To use asynchronous methods from otherwise-synchronous code (such as\n        unit tests), you can start and stop the event loop like this::\n\n          ioloop = IOLoop()\n          async_method(ioloop=ioloop, callback=ioloop.stop)\n          ioloop.start()\n\n        ``ioloop.start()`` will return after ``async_method`` has run\n        its callback, whether that callback was invoked before or\n        after ``ioloop.start``.\n\n        Note that even after `stop` has been called, the `IOLoop` is not\n        completely stopped until `IOLoop.start` has also returned.\n        Some work that was scheduled before the call to `stop` may still\n        be run before the `IOLoop` shuts down.\n        \"\"\"\n        raise NotImplementedError()\n\n    def run_sync(self, func, timeout=None):\n        \"\"\"Starts the `IOLoop`, runs the given function, and stops the loop.\n\n        The function must return either a yieldable object or\n        ``None``. If the function returns a yieldable object, the\n        `IOLoop` will run until the yieldable is resolved (and\n        `run_sync()` will return the yieldable's result). If it raises\n        an exception, the `IOLoop` will stop and the exception will be\n        re-raised to the caller.\n\n        The keyword-only argument ``timeout`` may be used to set\n        a maximum duration for the function.  If the timeout expires,\n        a `tornado.util.TimeoutError` is raised.\n\n        This method is useful in conjunction with `tornado.gen.coroutine`\n        to allow asynchronous calls in a ``main()`` function::\n\n            @gen.coroutine\n            def main():\n                # do stuff...\n\n            if __name__ == '__main__':\n                IOLoop.current().run_sync(main)\n\n        .. versionchanged:: 4.3\n           Returning a non-``None``, non-yieldable value is now an error.\n\n        .. versionchanged:: 5.0\n           If a timeout occurs, the ``func`` coroutine will be cancelled.\n        \"\"\"\n        future_cell = [None]\n\n        def run():\n            try:\n                result = func()\n                if result is not None:\n                    from tornado.gen import convert_yielded\n                    result = convert_yielded(result)\n            except Exception:\n                future_cell[0] = Future()\n                future_set_exc_info(future_cell[0], sys.exc_info())\n            else:\n                if is_future(result):\n                    future_cell[0] = result\n                else:\n                    future_cell[0] = Future()\n                    future_cell[0].set_result(result)\n            self.add_future(future_cell[0], lambda future: self.stop())\n        self.add_callback(run)\n        if timeout is not None:\n            def timeout_callback():\n                # If we can cancel the future, do so and wait on it. If not,\n                # Just stop the loop and return with the task still pending.\n                # (If we neither cancel nor wait for the task, a warning\n                # will be logged).\n                if not future_cell[0].cancel():\n                    self.stop()\n            timeout_handle = self.add_timeout(self.time() + timeout, timeout_callback)\n        self.start()\n        if timeout is not None:\n            self.remove_timeout(timeout_handle)\n        if future_cell[0].cancelled() or not future_cell[0].done():\n            raise TimeoutError('Operation timed out after %s seconds' % timeout)\n        return future_cell[0].result()\n\n    def time(self):\n        \"\"\"Returns the current time according to the `IOLoop`'s clock.\n\n        The return value is a floating-point number relative to an\n        unspecified time in the past.\n\n        By default, the `IOLoop`'s time function is `time.time`.  However,\n        it may be configured to use e.g. `time.monotonic` instead.\n        Calls to `add_timeout` that pass a number instead of a\n        `datetime.timedelta` should use this function to compute the\n        appropriate time, so they can work no matter what time function\n        is chosen.\n        \"\"\"\n        return time.time()\n\n    def add_timeout(self, deadline, callback, *args, **kwargs):\n        \"\"\"Runs the ``callback`` at the time ``deadline`` from the I/O loop.\n\n        Returns an opaque handle that may be passed to\n        `remove_timeout` to cancel.\n\n        ``deadline`` may be a number denoting a time (on the same\n        scale as `IOLoop.time`, normally `time.time`), or a\n        `datetime.timedelta` object for a deadline relative to the\n        current time.  Since Tornado 4.0, `call_later` is a more\n        convenient alternative for the relative case since it does not\n        require a timedelta object.\n\n        Note that it is not safe to call `add_timeout` from other threads.\n        Instead, you must use `add_callback` to transfer control to the\n        `IOLoop`'s thread, and then call `add_timeout` from there.\n\n        Subclasses of IOLoop must implement either `add_timeout` or\n        `call_at`; the default implementations of each will call\n        the other.  `call_at` is usually easier to implement, but\n        subclasses that wish to maintain compatibility with Tornado\n        versions prior to 4.0 must use `add_timeout` instead.\n\n        .. versionchanged:: 4.0\n           Now passes through ``*args`` and ``**kwargs`` to the callback.\n        \"\"\"\n        if isinstance(deadline, numbers.Real):\n            return self.call_at(deadline, callback, *args, **kwargs)\n        elif isinstance(deadline, datetime.timedelta):\n            return self.call_at(self.time() + timedelta_to_seconds(deadline),\n                                callback, *args, **kwargs)\n        else:\n            raise TypeError(\"Unsupported deadline %r\" % deadline)\n\n    def call_later(self, delay, callback, *args, **kwargs):\n        \"\"\"Runs the ``callback`` after ``delay`` seconds have passed.\n\n        Returns an opaque handle that may be passed to `remove_timeout`\n        to cancel.  Note that unlike the `asyncio` method of the same\n        name, the returned object does not have a ``cancel()`` method.\n\n        See `add_timeout` for comments on thread-safety and subclassing.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        return self.call_at(self.time() + delay, callback, *args, **kwargs)\n\n    def call_at(self, when, callback, *args, **kwargs):\n        \"\"\"Runs the ``callback`` at the absolute time designated by ``when``.\n\n        ``when`` must be a number using the same reference point as\n        `IOLoop.time`.\n\n        Returns an opaque handle that may be passed to `remove_timeout`\n        to cancel.  Note that unlike the `asyncio` method of the same\n        name, the returned object does not have a ``cancel()`` method.\n\n        See `add_timeout` for comments on thread-safety and subclassing.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        return self.add_timeout(when, callback, *args, **kwargs)\n\n    def remove_timeout(self, timeout):\n        \"\"\"Cancels a pending timeout.\n\n        The argument is a handle as returned by `add_timeout`.  It is\n        safe to call `remove_timeout` even if the callback has already\n        been run.\n        \"\"\"\n        raise NotImplementedError()\n\n    def add_callback(self, callback, *args, **kwargs):\n        \"\"\"Calls the given callback on the next I/O loop iteration.\n\n        It is safe to call this method from any thread at any time,\n        except from a signal handler.  Note that this is the **only**\n        method in `IOLoop` that makes this thread-safety guarantee; all\n        other interaction with the `IOLoop` must be done from that\n        `IOLoop`'s thread.  `add_callback()` may be used to transfer\n        control from other threads to the `IOLoop`'s thread.\n\n        To add a callback from a signal handler, see\n        `add_callback_from_signal`.\n        \"\"\"\n        raise NotImplementedError()\n\n    def add_callback_from_signal(self, callback, *args, **kwargs):\n        \"\"\"Calls the given callback on the next I/O loop iteration.\n\n        Safe for use from a Python signal handler; should not be used\n        otherwise.\n\n        Callbacks added with this method will be run without any\n        `.stack_context`, to avoid picking up the context of the function\n        that was interrupted by the signal.\n        \"\"\"\n        raise NotImplementedError()\n\n    def spawn_callback(self, callback, *args, **kwargs):\n        \"\"\"Calls the given callback on the next IOLoop iteration.\n\n        Unlike all other callback-related methods on IOLoop,\n        ``spawn_callback`` does not associate the callback with its caller's\n        ``stack_context``, so it is suitable for fire-and-forget callbacks\n        that should not interfere with the caller.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        with stack_context.NullContext():\n            self.add_callback(callback, *args, **kwargs)\n\n    def add_future(self, future, callback):\n        \"\"\"Schedules a callback on the ``IOLoop`` when the given\n        `.Future` is finished.\n\n        The callback is invoked with one argument, the\n        `.Future`.\n        \"\"\"\n        assert is_future(future)\n        callback = stack_context.wrap(callback)\n        future_add_done_callback(\n            future, lambda future: self.add_callback(callback, future))\n\n    def run_in_executor(self, executor, func, *args):\n        \"\"\"Runs a function in a ``concurrent.futures.Executor``. If\n        ``executor`` is ``None``, the IO loop's default executor will be used.\n\n        Use `functools.partial` to pass keyword arguments to ``func``.\n\n        .. versionadded:: 5.0\n        \"\"\"\n        if ThreadPoolExecutor is None:\n            raise RuntimeError(\n                \"concurrent.futures is required to use IOLoop.run_in_executor\")\n\n        if executor is None:\n            if not hasattr(self, '_executor'):\n                from tornado.process import cpu_count\n                self._executor = ThreadPoolExecutor(max_workers=(cpu_count() * 5))\n            executor = self._executor\n        c_future = executor.submit(func, *args)\n        # Concurrent Futures are not usable with await. Wrap this in a\n        # Tornado Future instead, using self.add_future for thread-safety.\n        t_future = Future()\n        self.add_future(c_future, lambda f: chain_future(f, t_future))\n        return t_future\n\n    def set_default_executor(self, executor):\n        \"\"\"Sets the default executor to use with :meth:`run_in_executor`.\n\n        .. versionadded:: 5.0\n        \"\"\"\n        self._executor = executor\n\n    def _run_callback(self, callback):\n        \"\"\"Runs a callback with error handling.\n\n        For use in subclasses.\n        \"\"\"\n        try:\n            ret = callback()\n            if ret is not None:\n                from tornado import gen\n                # Functions that return Futures typically swallow all\n                # exceptions and store them in the Future.  If a Future\n                # makes it out to the IOLoop, ensure its exception (if any)\n                # gets logged too.\n                try:\n                    ret = gen.convert_yielded(ret)\n                except gen.BadYieldError:\n                    # It's not unusual for add_callback to be used with\n                    # methods returning a non-None and non-yieldable\n                    # result, which should just be ignored.\n                    pass\n                else:\n                    self.add_future(ret, self._discard_future_result)\n        except Exception:\n            self.handle_callback_exception(callback)\n\n    def _discard_future_result(self, future):\n        \"\"\"Avoid unhandled-exception warnings from spawned coroutines.\"\"\"\n        future.result()\n\n    def handle_callback_exception(self, callback):\n        \"\"\"This method is called whenever a callback run by the `IOLoop`\n        throws an exception.\n\n        By default simply logs the exception as an error.  Subclasses\n        may override this method to customize reporting of exceptions.\n\n        The exception itself is not passed explicitly, but is available\n        in `sys.exc_info`.\n        \"\"\"\n        app_log.error(\"Exception in callback %r\", callback, exc_info=True)\n\n    def split_fd(self, fd):\n        \"\"\"Returns an (fd, obj) pair from an ``fd`` parameter.\n\n        We accept both raw file descriptors and file-like objects as\n        input to `add_handler` and related methods.  When a file-like\n        object is passed, we must retain the object itself so we can\n        close it correctly when the `IOLoop` shuts down, but the\n        poller interfaces favor file descriptors (they will accept\n        file-like objects and call ``fileno()`` for you, but they\n        always return the descriptor itself).\n\n        This method is provided for use by `IOLoop` subclasses and should\n        not generally be used by application code.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        try:\n            return fd.fileno(), fd\n        except AttributeError:\n            return fd, fd\n\n    def close_fd(self, fd):\n        \"\"\"Utility method to close an ``fd``.\n\n        If ``fd`` is a file-like object, we close it directly; otherwise\n        we use `os.close`.\n\n        This method is provided for use by `IOLoop` subclasses (in\n        implementations of ``IOLoop.close(all_fds=True)`` and should\n        not generally be used by application code.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        try:\n            try:\n                fd.close()\n            except AttributeError:\n                os.close(fd)\n        except OSError:\n            pass\n\n\nclass PollIOLoop(IOLoop):\n    \"\"\"Base class for IOLoops built around a select-like function.\n\n    For concrete implementations, see `tornado.platform.epoll.EPollIOLoop`\n    (Linux), `tornado.platform.kqueue.KQueueIOLoop` (BSD and Mac), or\n    `tornado.platform.select.SelectIOLoop` (all platforms).\n    \"\"\"\n    def initialize(self, impl, time_func=None, **kwargs):\n        super(PollIOLoop, self).initialize(**kwargs)\n        self._impl = impl\n        if hasattr(self._impl, 'fileno'):\n            set_close_exec(self._impl.fileno())\n        self.time_func = time_func or time.time\n        self._handlers = {}\n        self._events = {}\n        self._callbacks = collections.deque()\n        self._timeouts = []\n        self._cancellations = 0\n        self._running = False\n        self._stopped = False\n        self._closing = False\n        self._thread_ident = None\n        self._pid = os.getpid()\n        self._blocking_signal_threshold = None\n        self._timeout_counter = itertools.count()\n\n        # Create a pipe that we send bogus data to when we want to wake\n        # the I/O loop when it is idle\n        self._waker = Waker()\n        self.add_handler(self._waker.fileno(),\n                         lambda fd, events: self._waker.consume(),\n                         self.READ)\n\n    @classmethod\n    def configurable_base(cls):\n        return PollIOLoop\n\n    @classmethod\n    def configurable_default(cls):\n        if hasattr(select, \"epoll\"):\n            from tornado.platform.epoll import EPollIOLoop\n            return EPollIOLoop\n        if hasattr(select, \"kqueue\"):\n            # Python 2.6+ on BSD or Mac\n            from tornado.platform.kqueue import KQueueIOLoop\n            return KQueueIOLoop\n        from tornado.platform.select import SelectIOLoop\n        return SelectIOLoop\n\n    def close(self, all_fds=False):\n        self._closing = True\n        self.remove_handler(self._waker.fileno())\n        if all_fds:\n            for fd, handler in list(self._handlers.values()):\n                self.close_fd(fd)\n        self._waker.close()\n        self._impl.close()\n        self._callbacks = None\n        self._timeouts = None\n        if hasattr(self, '_executor'):\n            self._executor.shutdown()\n\n    def add_handler(self, fd, handler, events):\n        fd, obj = self.split_fd(fd)\n        self._handlers[fd] = (obj, stack_context.wrap(handler))\n        self._impl.register(fd, events | self.ERROR)\n\n    def update_handler(self, fd, events):\n        fd, obj = self.split_fd(fd)\n        self._impl.modify(fd, events | self.ERROR)\n\n    def remove_handler(self, fd):\n        fd, obj = self.split_fd(fd)\n        self._handlers.pop(fd, None)\n        self._events.pop(fd, None)\n        try:\n            self._impl.unregister(fd)\n        except Exception:\n            gen_log.debug(\"Error deleting fd from IOLoop\", exc_info=True)\n\n    def set_blocking_signal_threshold(self, seconds, action):\n        if not hasattr(signal, \"setitimer\"):\n            gen_log.error(\"set_blocking_signal_threshold requires a signal module \"\n                          \"with the setitimer method\")\n            return\n        self._blocking_signal_threshold = seconds\n        if seconds is not None:\n            signal.signal(signal.SIGALRM,\n                          action if action is not None else signal.SIG_DFL)\n\n    def start(self):\n        if self._running:\n            raise RuntimeError(\"IOLoop is already running\")\n        if os.getpid() != self._pid:\n            raise RuntimeError(\"Cannot share PollIOLoops across processes\")\n        self._setup_logging()\n        if self._stopped:\n            self._stopped = False\n            return\n        old_current = IOLoop.current(instance=False)\n        if old_current is not self:\n            self.make_current()\n        self._thread_ident = thread.get_ident()\n        self._running = True\n\n        # signal.set_wakeup_fd closes a race condition in event loops:\n        # a signal may arrive at the beginning of select/poll/etc\n        # before it goes into its interruptible sleep, so the signal\n        # will be consumed without waking the select.  The solution is\n        # for the (C, synchronous) signal handler to write to a pipe,\n        # which will then be seen by select.\n        #\n        # In python's signal handling semantics, this only matters on the\n        # main thread (fortunately, set_wakeup_fd only works on the main\n        # thread and will raise a ValueError otherwise).\n        #\n        # If someone has already set a wakeup fd, we don't want to\n        # disturb it.  This is an issue for twisted, which does its\n        # SIGCHLD processing in response to its own wakeup fd being\n        # written to.  As long as the wakeup fd is registered on the IOLoop,\n        # the loop will still wake up and everything should work.\n        old_wakeup_fd = None\n        if hasattr(signal, 'set_wakeup_fd') and os.name == 'posix':\n            # requires python 2.6+, unix.  set_wakeup_fd exists but crashes\n            # the python process on windows.\n            try:\n                old_wakeup_fd = signal.set_wakeup_fd(self._waker.write_fileno())\n                if old_wakeup_fd != -1:\n                    # Already set, restore previous value.  This is a little racy,\n                    # but there's no clean get_wakeup_fd and in real use the\n                    # IOLoop is just started once at the beginning.\n                    signal.set_wakeup_fd(old_wakeup_fd)\n                    old_wakeup_fd = None\n            except ValueError:\n                # Non-main thread, or the previous value of wakeup_fd\n                # is no longer valid.\n                old_wakeup_fd = None\n\n        try:\n            while True:\n                # Prevent IO event starvation by delaying new callbacks\n                # to the next iteration of the event loop.\n                ncallbacks = len(self._callbacks)\n\n                # Add any timeouts that have come due to the callback list.\n                # Do not run anything until we have determined which ones\n                # are ready, so timeouts that call add_timeout cannot\n                # schedule anything in this iteration.\n                due_timeouts = []\n                if self._timeouts:\n                    now = self.time()\n                    while self._timeouts:\n                        if self._timeouts[0].callback is None:\n                            # The timeout was cancelled.  Note that the\n                            # cancellation check is repeated below for timeouts\n                            # that are cancelled by another timeout or callback.\n                            heapq.heappop(self._timeouts)\n                            self._cancellations -= 1\n                        elif self._timeouts[0].deadline <= now:\n                            due_timeouts.append(heapq.heappop(self._timeouts))\n                        else:\n                            break\n                    if (self._cancellations > 512 and\n                            self._cancellations > (len(self._timeouts) >> 1)):\n                        # Clean up the timeout queue when it gets large and it's\n                        # more than half cancellations.\n                        self._cancellations = 0\n                        self._timeouts = [x for x in self._timeouts\n                                          if x.callback is not None]\n                        heapq.heapify(self._timeouts)\n\n                for i in range(ncallbacks):\n                    self._run_callback(self._callbacks.popleft())\n                for timeout in due_timeouts:\n                    if timeout.callback is not None:\n                        self._run_callback(timeout.callback)\n                # Closures may be holding on to a lot of memory, so allow\n                # them to be freed before we go into our poll wait.\n                due_timeouts = timeout = None\n\n                if self._callbacks:\n                    # If any callbacks or timeouts called add_callback,\n                    # we don't want to wait in poll() before we run them.\n                    poll_timeout = 0.0\n                elif self._timeouts:\n                    # If there are any timeouts, schedule the first one.\n                    # Use self.time() instead of 'now' to account for time\n                    # spent running callbacks.\n                    poll_timeout = self._timeouts[0].deadline - self.time()\n                    poll_timeout = max(0, min(poll_timeout, _POLL_TIMEOUT))\n                else:\n                    # No timeouts and no callbacks, so use the default.\n                    poll_timeout = _POLL_TIMEOUT\n\n                if not self._running:\n                    break\n\n                if self._blocking_signal_threshold is not None:\n                    # clear alarm so it doesn't fire while poll is waiting for\n                    # events.\n                    signal.setitimer(signal.ITIMER_REAL, 0, 0)\n\n                try:\n                    event_pairs = self._impl.poll(poll_timeout)\n                except Exception as e:\n                    # Depending on python version and IOLoop implementation,\n                    # different exception types may be thrown and there are\n                    # two ways EINTR might be signaled:\n                    # * e.errno == errno.EINTR\n                    # * e.args is like (errno.EINTR, 'Interrupted system call')\n                    if errno_from_exception(e) == errno.EINTR:\n                        continue\n                    else:\n                        raise\n\n                if self._blocking_signal_threshold is not None:\n                    signal.setitimer(signal.ITIMER_REAL,\n                                     self._blocking_signal_threshold, 0)\n\n                # Pop one fd at a time from the set of pending fds and run\n                # its handler. Since that handler may perform actions on\n                # other file descriptors, there may be reentrant calls to\n                # this IOLoop that modify self._events\n                self._events.update(event_pairs)\n                while self._events:\n                    fd, events = self._events.popitem()\n                    try:\n                        fd_obj, handler_func = self._handlers[fd]\n                        handler_func(fd_obj, events)\n                    except (OSError, IOError) as e:\n                        if errno_from_exception(e) == errno.EPIPE:\n                            # Happens when the client closes the connection\n                            pass\n                        else:\n                            self.handle_callback_exception(self._handlers.get(fd))\n                    except Exception:\n                        self.handle_callback_exception(self._handlers.get(fd))\n                fd_obj = handler_func = None\n\n        finally:\n            # reset the stopped flag so another start/stop pair can be issued\n            self._stopped = False\n            if self._blocking_signal_threshold is not None:\n                signal.setitimer(signal.ITIMER_REAL, 0, 0)\n            if old_current is None:\n                IOLoop.clear_current()\n            elif old_current is not self:\n                old_current.make_current()\n            if old_wakeup_fd is not None:\n                signal.set_wakeup_fd(old_wakeup_fd)\n\n    def stop(self):\n        self._running = False\n        self._stopped = True\n        self._waker.wake()\n\n    def time(self):\n        return self.time_func()\n\n    def call_at(self, deadline, callback, *args, **kwargs):\n        timeout = _Timeout(\n            deadline,\n            functools.partial(stack_context.wrap(callback), *args, **kwargs),\n            self)\n        heapq.heappush(self._timeouts, timeout)\n        return timeout\n\n    def remove_timeout(self, timeout):\n        # Removing from a heap is complicated, so just leave the defunct\n        # timeout object in the queue (see discussion in\n        # http://docs.python.org/library/heapq.html).\n        # If this turns out to be a problem, we could add a garbage\n        # collection pass whenever there are too many dead timeouts.\n        timeout.callback = None\n        self._cancellations += 1\n\n    def add_callback(self, callback, *args, **kwargs):\n        if self._closing:\n            return\n        # Blindly insert into self._callbacks. This is safe even\n        # from signal handlers because deque.append is atomic.\n        self._callbacks.append(functools.partial(\n            stack_context.wrap(callback), *args, **kwargs))\n        if thread.get_ident() != self._thread_ident:\n            # This will write one byte but Waker.consume() reads many\n            # at once, so it's ok to write even when not strictly\n            # necessary.\n            self._waker.wake()\n        else:\n            # If we're on the IOLoop's thread, we don't need to wake anyone.\n            pass\n\n    def add_callback_from_signal(self, callback, *args, **kwargs):\n        with stack_context.NullContext():\n            self.add_callback(callback, *args, **kwargs)\n\n\nclass _Timeout(object):\n    \"\"\"An IOLoop timeout, a UNIX timestamp and a callback\"\"\"\n\n    # Reduce memory overhead when there are lots of pending callbacks\n    __slots__ = ['deadline', 'callback', 'tdeadline']\n\n    def __init__(self, deadline, callback, io_loop):\n        if not isinstance(deadline, numbers.Real):\n            raise TypeError(\"Unsupported deadline %r\" % deadline)\n        self.deadline = deadline\n        self.callback = callback\n        self.tdeadline = (deadline, next(io_loop._timeout_counter))\n\n    # Comparison methods to sort by deadline, with object id as a tiebreaker\n    # to guarantee a consistent ordering.  The heapq module uses __le__\n    # in python2.5, and __lt__ in 2.6+ (sort() and most other comparisons\n    # use __lt__).\n    def __lt__(self, other):\n        return self.tdeadline < other.tdeadline\n\n    def __le__(self, other):\n        return self.tdeadline <= other.tdeadline\n\n\nclass PeriodicCallback(object):\n    \"\"\"Schedules the given callback to be called periodically.\n\n    The callback is called every ``callback_time`` milliseconds.\n    Note that the timeout is given in milliseconds, while most other\n    time-related functions in Tornado use seconds.\n\n    If the callback runs for longer than ``callback_time`` milliseconds,\n    subsequent invocations will be skipped to get back on schedule.\n\n    `start` must be called after the `PeriodicCallback` is created.\n\n    .. versionchanged:: 5.0\n       The ``io_loop`` argument (deprecated since version 4.1) has been removed.\n    \"\"\"\n    def __init__(self, callback, callback_time):\n        self.callback = callback\n        if callback_time <= 0:\n            raise ValueError(\"Periodic callback must have a positive callback_time\")\n        self.callback_time = callback_time\n        self._running = False\n        self._timeout = None\n\n    def start(self):\n        \"\"\"Starts the timer.\"\"\"\n        # Looking up the IOLoop here allows to first instantiate the\n        # PeriodicCallback in another thread, then start it using\n        # IOLoop.add_callback().\n        self.io_loop = IOLoop.current()\n        self._running = True\n        self._next_timeout = self.io_loop.time()\n        self._schedule_next()\n\n    def stop(self):\n        \"\"\"Stops the timer.\"\"\"\n        self._running = False\n        if self._timeout is not None:\n            self.io_loop.remove_timeout(self._timeout)\n            self._timeout = None\n\n    def is_running(self):\n        \"\"\"Return True if this `.PeriodicCallback` has been started.\n\n        .. versionadded:: 4.1\n        \"\"\"\n        return self._running\n\n    def _run(self):\n        if not self._running:\n            return\n        try:\n            return self.callback()\n        except Exception:\n            self.io_loop.handle_callback_exception(self.callback)\n        finally:\n            self._schedule_next()\n\n    def _schedule_next(self):\n        if self._running:\n            current_time = self.io_loop.time()\n\n            if self._next_timeout <= current_time:\n                callback_time_sec = self.callback_time / 1000.0\n                self._next_timeout += (math.floor((current_time - self._next_timeout) /\n                                                  callback_time_sec) + 1) * callback_time_sec\n\n            self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run)\n"}
A user will ask you to solve a task. You should first draft your thinking process (inner monologue). Then, generate the solution.

Your response format must follow the template below:
<think>
Your thoughts or/and draft, like working through an exercise on scratch paper. Be as casual and as long as you want until you are confident to generate a correct solution.
</think>
<solution>
Final solution presented to the user.
</solution>
system
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** `PeriodicCallback` Missing `_update_next` Method Causing Test Failures

**Description:**
When running tests designed to verify the mathematical calculations of `PeriodicCallback`, an `AttributeError` is raised because the `_update_next` method does not exist in the `PeriodicCallback` class. This prevents the tests from executing the intended logic separately from the IOLoop configuration.

**Example Code:**
```python
class TestPeriodicCallbackMath(unittest.TestCase):
    def simulate_calls(self, pc, durations):
        calls = []
        now = 1000
        pc._next_timeout = now
        for d in durations:
            pc._update_next(now)
            calls.append(pc._next_timeout)
            now = pc._next_timeout + d
        return calls

    def test_basic(self):
        pc = PeriodicCallback(None, 10000)
        self.simulate_calls(pc, [0] * 5)
```

**Expected Behavior:**
The `PeriodicCallback` class should include the `_update_next` method, allowing the mathematical scheduling logic to be tested independently. This method should correctly update the next timeout based on the current time and callback interval.

**Actual Behavior:**
Running the tests results in the following error:
```
AttributeError: 'PeriodicCallback' object has no attribute '_update_next'
```
This error prevents the math-related tests from executing, hindering the ability to verify the correctness of the periodic callback scheduling.

[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### tornado/ioloop.py
#
# Copyright 2009 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

"""An I/O event loop for non-blocking sockets.

On Python 3, `.IOLoop` is a wrapper around the `asyncio` event loop.

Typical applications will use a single `IOLoop` object, accessed via
`IOLoop.current` class method. The `IOLoop.start` method (or
equivalently, `asyncio.AbstractEventLoop.run_forever`) should usually
be called at the end of the ``main()`` function. Atypical applications
may use more than one `IOLoop`, such as one `IOLoop` per thread, or
per `unittest` case.

In addition to I/O events, the `IOLoop` can also schedule time-based
events. `IOLoop.add_timeout` is a non-blocking alternative to
`time.sleep`.

"""

from __future__ import absolute_import, division, print_function

import collections
import datetime
import errno
import functools
import heapq
import itertools
import logging
import numbers
import os
import select
import sys
import threading
import time
import traceback
import math

from tornado.concurrent import Future, is_future, chain_future, future_set_exc_info, future_add_done_callback  # noqa: E501
from tornado.log import app_log, gen_log
from tornado.platform.auto import set_close_exec, Waker
from tornado import stack_context
from tornado.util import (
    PY3, Configurable, errno_from_exception, timedelta_to_seconds,
    TimeoutError, unicode_type, import_object,
)

try:
    import signal
except ImportError:
    signal = None

try:
    from concurrent.futures import ThreadPoolExecutor
except ImportError:
    ThreadPoolExecutor = None

if PY3:
    import _thread as thread
else:
    import thread

try:
    import asyncio
except ImportError:
    asyncio = None


_POLL_TIMEOUT = 3600.0


class IOLoop(Configurable):
    """A level-triggered I/O loop.

    On Python 3, `IOLoop` is a wrapper around the `asyncio` event
    loop. On Python 2, it uses ``epoll`` (Linux) or ``kqueue`` (BSD
    and Mac OS X) if they are available, or else we fall back on
    select(). If you are implementing a system that needs to handle
    thousands of simultaneous connections, you should use a system
    that supports either ``epoll`` or ``kqueue``.

    Example usage for a simple TCP server:

    .. testcode::

        import errno
        import functools
        import socket

        import tornado.ioloop
        from tornado import gen
        from tornado.iostream import IOStream

        @gen.coroutine
        def handle_connection(connection, address):
            stream = IOStream(connection)
            message = yield stream.read_until_close()
            print("message from client:", message.decode().strip())

        def connection_ready(sock, fd, events):
            while True:
                try:
                    connection, address = sock.accept()
                except socket.error as e:
                    if e.args[0] not in (errno.EWOULDBLOCK, errno.EAGAIN):
                        raise
                    return
                connection.setblocking(0)
                handle_connection(connection, address)

        if __name__ == '__main__':
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            sock.setblocking(0)
            sock.bind(("", 8888))
            sock.listen(128)

            io_loop = tornado.ioloop.IOLoop.current()
            callback = functools.partial(connection_ready, sock)
            io_loop.add_handler(sock.fileno(), callback, io_loop.READ)
            io_loop.start()

    .. testoutput::
       :hide:

    By default, a newly-constructed `IOLoop` becomes the thread's current
    `IOLoop`, unless there already is a current `IOLoop`. This behavior
    can be controlled with the ``make_current`` argument to the `IOLoop`
    constructor: if ``make_current=True``, the new `IOLoop` will always
    try to become current and it raises an error if there is already a
    current instance. If ``make_current=False``, the new `IOLoop` will
    not try to become current.

    In general, an `IOLoop` cannot survive a fork or be shared across
    processes in any way. When multiple processes are being used, each
    process should create its own `IOLoop`, which also implies that
    any objects which depend on the `IOLoop` (such as
    `.AsyncHTTPClient`) must also be created in the child processes.
    As a guideline, anything that starts processes (including the
    `tornado.process` and `multiprocessing` modules) should do so as
    early as possible, ideally the first thing the application does
    after loading its configuration in ``main()``.

    .. versionchanged:: 4.2
       Added the ``make_current`` keyword argument to the `IOLoop`
       constructor.

    .. versionchanged:: 5.0

       Uses the `asyncio` event loop by default. The
       ``IOLoop.configure`` method cannot be used on Python 3 except
       to redundantly specify the `asyncio` event loop.

    """
    # Constants from the epoll module
    _EPOLLIN = 0x001
    _EPOLLPRI = 0x002
    _EPOLLOUT = 0x004
    _EPOLLERR = 0x008
    _EPOLLHUP = 0x010
    _EPOLLRDHUP = 0x2000
    _EPOLLONESHOT = (1 << 30)
    _EPOLLET = (1 << 31)

    # Our events map exactly to the epoll events
    NONE = 0
    READ = _EPOLLIN
    WRITE = _EPOLLOUT
    ERROR = _EPOLLERR | _EPOLLHUP

    # In Python 2, _current.instance points to the current IOLoop.
    _current = threading.local()

    # In Python 3, _ioloop_for_asyncio maps from asyncio loops to IOLoops.
    _ioloop_for_asyncio = dict()

    @classmethod
    def configure(cls, impl, **kwargs):
        if asyncio is not None:
            from tornado.platform.asyncio import BaseAsyncIOLoop

            if isinstance(impl, (str, unicode_type)):
                impl = import_object(impl)
            if not issubclass(impl, BaseAsyncIOLoop):
                raise RuntimeError(
                    "only AsyncIOLoop is allowed when asyncio is available")
        super(IOLoop, cls).configure(impl, **kwargs)

    @staticmethod
    def instance():
        """Deprecated alias for `IOLoop.current()`.

        .. versionchanged:: 5.0

           Previously, this method returned a global singleton
           `IOLoop`, in contrast with the per-thread `IOLoop` returned
           by `current()`. In nearly all cases the two were the same
           (when they differed, it was generally used from non-Tornado
           threads to communicate back to the main thread's `IOLoop`).
           This distinction is not present in `asyncio`, so in order
           to facilitate integration with that package `instance()`
           was changed to be an alias to `current()`. Applications
           using the cross-thread communications aspect of
           `instance()` should instead set their own global variable
           to point to the `IOLoop` they want to use.

        .. deprecated:: 5.0
        """
        return IOLoop.current()

    def install(self):
        """Deprecated alias for `make_current()`.

        .. versionchanged:: 5.0

           Previously, this method would set this `IOLoop` as the
           global singleton used by `IOLoop.instance()`. Now that
           `instance()` is an alias for `current()`, `install()`
           is an alias for `make_current()`.

        .. deprecated:: 5.0
        """
        self.make_current()

    @staticmethod
    def clear_instance():
        """Deprecated alias for `clear_current()`.

        .. versionchanged:: 5.0

           Previously, this method would clear the `IOLoop` used as
           the global singleton by `IOLoop.instance()`. Now that
           `instance()` is an alias for `current()`,
           `clear_instance()` is an alias for `clear_current()`.

        .. deprecated:: 5.0

        """
        IOLoop.clear_current()

    @staticmethod
    def current(instance=True):
        """Returns the current thread's `IOLoop`.

        If an `IOLoop` is currently running or has been marked as
        current by `make_current`, returns that instance.  If there is
        no current `IOLoop` and ``instance`` is true, creates one.

        .. versionchanged:: 4.1
           Added ``instance`` argument to control the fallback to
           `IOLoop.instance()`.
        .. versionchanged:: 5.0
           On Python 3, control of the current `IOLoop` is delegated
           to `asyncio`, with this and other methods as pass-through accessors.
           The ``instance`` argument now controls whether an `IOLoop`
           is created automatically when there is none, instead of
           whether we fall back to `IOLoop.instance()` (which is now
           an alias for this method). ``instance=False`` is deprecated,
           since even if we do not create an `IOLoop`, this method
           may initialize the asyncio loop.
        """
        if asyncio is None:
            current = getattr(IOLoop._current, "instance", None)
            if current is None and instance:
                current = IOLoop()
                if IOLoop._current.instance is not current:
                    raise RuntimeError("new IOLoop did not become current")
        else:
            try:
                loop = asyncio.get_event_loop()
            except (RuntimeError, AssertionError):
                if not instance:
                    return None
                raise
            try:
                return IOLoop._ioloop_for_asyncio[loop]
            except KeyError:
                if instance:
                    from tornado.platform.asyncio import AsyncIOMainLoop
                    current = AsyncIOMainLoop(make_current=True)
                else:
                    current = None
        return current

    def make_current(self):
        """Makes this the `IOLoop` for the current thread.

        An `IOLoop` automatically becomes current for its thread
        when it is started, but it is sometimes useful to call
        `make_current` explicitly before starting the `IOLoop`,
        so that code run at startup time can find the right
        instance.

        .. versionchanged:: 4.1
           An `IOLoop` created while there is no current `IOLoop`
           will automatically become current.

        .. versionchanged:: 5.0
           This method also sets the current `asyncio` event loop.
        """
        # The asyncio event loops override this method.
        assert asyncio is None
        old = getattr(IOLoop._current, "instance", None)
        if old is not None:
            old.clear_current()
        IOLoop._current.instance = self

    @staticmethod
    def clear_current():
        """Clears the `IOLoop` for the current thread.

        Intended primarily for use by test frameworks in between tests.

        .. versionchanged:: 5.0
           This method also clears the current `asyncio` event loop.
        """
        old = IOLoop.current(instance=False)
        if old is not None:
            old._clear_current_hook()
        if asyncio is None:
            IOLoop._current.instance = None

    def _clear_current_hook(self):
        """Instance method called when an IOLoop ceases to be current.

        May be overridden by subclasses as a counterpart to make_current.
        """
        pass

    @classmethod
    def configurable_base(cls):
        return IOLoop

    @classmethod
    def configurable_default(cls):
        if asyncio is not None:
            from tornado.platform.asyncio import AsyncIOLoop
            return AsyncIOLoop
        return PollIOLoop

    def initialize(self, make_current=None):
        if make_current is None:
            if IOLoop.current(instance=False) is None:
                self.make_current()
        elif make_current:
            current = IOLoop.current(instance=False)
            # AsyncIO loops can already be current by this point.
            if current is not None and current is not self:
                raise RuntimeError("current IOLoop already exists")
            self.make_current()

    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 add_handler(self, fd, handler, events):
        """Registers the given handler to receive the given events for ``fd``.

        The ``fd`` argument may either be an integer file descriptor or
        a file-like object with a ``fileno()`` method (and optionally a
        ``close()`` method, which may be called when the `IOLoop` is shut
        down).

        The ``events`` argument is a bitwise or of the constants
        ``IOLoop.READ``, ``IOLoop.WRITE``, and ``IOLoop.ERROR``.

        When an event occurs, ``handler(fd, events)`` will be run.

        .. versionchanged:: 4.0
           Added the ability to pass file-like objects in addition to
           raw file descriptors.
        """
        raise NotImplementedError()

    def update_handler(self, fd, events):
        """Changes the events we listen for ``fd``.

        .. versionchanged:: 4.0
           Added the ability to pass file-like objects in addition to
           raw file descriptors.
        """
        raise NotImplementedError()

    def remove_handler(self, fd):
        """Stop listening for events on ``fd``.

        .. versionchanged:: 4.0
           Added the ability to pass file-like objects in addition to
           raw file descriptors.
        """
        raise NotImplementedError()

    def set_blocking_signal_threshold(self, seconds, action):
        """Sends a signal if the `IOLoop` is blocked for more than
        ``s`` seconds.

        Pass ``seconds=None`` to disable.  Requires Python 2.6 on a unixy
        platform.

        The action parameter is a Python signal handler.  Read the
        documentation for the `signal` module for more information.
        If ``action`` is None, the process will be killed if it is
        blocked for too long.

        .. deprecated:: 5.0

           Not implemented on the `asyncio` event loop. Use the environment
           variable ``PYTHONASYNCIODEBUG=1`` instead.
        """
        raise NotImplementedError()

    def set_blocking_log_threshold(self, seconds):
        """Logs a stack trace if the `IOLoop` is blocked for more than
        ``s`` seconds.

        Equivalent to ``set_blocking_signal_threshold(seconds,
        self.log_stack)``

        .. deprecated:: 5.0

           Not implemented on the `asyncio` event loop. Use the environment
           variable ``PYTHONASYNCIODEBUG=1`` instead.
        """
        self.set_blocking_signal_threshold(seconds, self.log_stack)

    def log_stack(self, signal, frame):
        """Signal handler to log the stack trace of the current thread.

        For use with `set_blocking_signal_threshold`.
        """
        gen_log.warning('IOLoop blocked for %f seconds in\n%s',
                        self._blocking_signal_threshold,
                        ''.join(traceback.format_stack(frame)))

    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 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 run_sync(self, func, timeout=None):
        """Starts the `IOLoop`, runs the given function, and stops the loop.

        The function must return either a yieldable object or
        ``None``. If the function returns a yieldable object, the
        `IOLoop` will run until the yieldable is resolved (and
        `run_sync()` will return the yieldable's result). If it raises
        an exception, the `IOLoop` will stop and the exception will be
        re-raised to the caller.

        The keyword-only argument ``timeout`` may be used to set
        a maximum duration for the function.  If the timeout expires,
        a `tornado.util.TimeoutError` is raised.

        This method is useful in conjunction with `tornado.gen.coroutine`
        to allow asynchronous calls in a ``main()`` function::

            @gen.coroutine
            def main():
                # do stuff...

            if __name__ == '__main__':
                IOLoop.current().run_sync(main)

        .. versionchanged:: 4.3
           Returning a non-``None``, non-yieldable value is now an error.

        .. versionchanged:: 5.0
           If a timeout occurs, the ``func`` coroutine will be cancelled.
        """
        future_cell = [None]

        def run():
            try:
                result = func()
                if result is not None:
                    from tornado.gen import convert_yielded
                    result = convert_yielded(result)
            except Exception:
                future_cell[0] = Future()
                future_set_exc_info(future_cell[0], sys.exc_info())
            else:
                if is_future(result):
                    future_cell[0] = result
                else:
                    future_cell[0] = Future()
                    future_cell[0].set_result(result)
            self.add_future(future_cell[0], lambda future: self.stop())
        self.add_callback(run)
        if timeout is not None:
            def timeout_callback():
                # If we can cancel the future, do so and wait on it. If not,
                # Just stop the loop and return with the task still pending.
                # (If we neither cancel nor wait for the task, a warning
                # will be logged).
                if not future_cell[0].cancel():
                    self.stop()
            timeout_handle = self.add_timeout(self.time() + timeout, timeout_callback)
        self.start()
        if timeout is not None:
            self.remove_timeout(timeout_handle)
        if future_cell[0].cancelled() or not future_cell[0].done():
            raise TimeoutError('Operation timed out after %s seconds' % timeout)
        return future_cell[0].result()

    def time(self):
        """Returns the current time according to the `IOLoop`'s clock.

        The return value is a floating-point number relative to an
        unspecified time in the past.

        By default, the `IOLoop`'s time function is `time.time`.  However,
        it may be configured to use e.g. `time.monotonic` instead.
        Calls to `add_timeout` that pass a number instead of a
        `datetime.timedelta` should use this function to compute the
        appropriate time, so they can work no matter what time function
        is chosen.
        """
        return time.time()

    def add_timeout(self, deadline, callback, *args, **kwargs):
        """Runs the ``callback`` at the time ``deadline`` from the I/O loop.

        Returns an opaque handle that may be passed to
        `remove_timeout` to cancel.

        ``deadline`` may be a number denoting a time (on the same
        scale as `IOLoop.time`, normally `time.time`), or a
        `datetime.timedelta` object for a deadline relative to the
        current time.  Since Tornado 4.0, `call_later` is a more
        convenient alternative for the relative case since it does not
        require a timedelta object.

        Note that it is not safe to call `add_timeout` from other threads.
        Instead, you must use `add_callback` to transfer control to the
        `IOLoop`'s thread, and then call `add_timeout` from there.

        Subclasses of IOLoop must implement either `add_timeout` or
        `call_at`; the default implementations of each will call
        the other.  `call_at` is usually easier to implement, but
        subclasses that wish to maintain compatibility with Tornado
        versions prior to 4.0 must use `add_timeout` instead.

        .. versionchanged:: 4.0
           Now passes through ``*args`` and ``**kwargs`` to the callback.
        """
        if isinstance(deadline, numbers.Real):
            return self.call_at(deadline, callback, *args, **kwargs)
        elif isinstance(deadline, datetime.timedelta):
            return self.call_at(self.time() + timedelta_to_seconds(deadline),
                                callback, *args, **kwargs)
        else:
            raise TypeError("Unsupported deadline %r" % deadline)

    def call_later(self, delay, callback, *args, **kwargs):
        """Runs the ``callback`` after ``delay`` seconds have passed.

        Returns an opaque handle that may be passed to `remove_timeout`
        to cancel.  Note that unlike the `asyncio` method of the same
        name, the returned object does not have a ``cancel()`` method.

        See `add_timeout` for comments on thread-safety and subclassing.

        .. versionadded:: 4.0
        """
        return self.call_at(self.time() + delay, callback, *args, **kwargs)

    def call_at(self, when, callback, *args, **kwargs):
        """Runs the ``callback`` at the absolute time designated by ``when``.

        ``when`` must be a number using the same reference point as
        `IOLoop.time`.

        Returns an opaque handle that may be passed to `remove_timeout`
        to cancel.  Note that unlike the `asyncio` method of the same
        name, the returned object does not have a ``cancel()`` method.

        See `add_timeout` for comments on thread-safety and subclassing.

        .. versionadded:: 4.0
        """
        return self.add_timeout(when, callback, *args, **kwargs)

    def remove_timeout(self, timeout):
        """Cancels a pending timeout.

        The argument is a handle as returned by `add_timeout`.  It is
        safe to call `remove_timeout` even if the callback has already
        been run.
        """
        raise NotImplementedError()

    def add_callback(self, callback, *args, **kwargs):
        """Calls the given callback on the next I/O loop iteration.

        It is safe to call this method from any thread at any time,
        except from a signal handler.  Note that this is the **only**
        method in `IOLoop` that makes this thread-safety guarantee; all
        other interaction with the `IOLoop` must be done from that
        `IOLoop`'s thread.  `add_callback()` may be used to transfer
        control from other threads to the `IOLoop`'s thread.

        To add a callback from a signal handler, see
        `add_callback_from_signal`.
        """
        raise NotImplementedError()

    def add_callback_from_signal(self, callback, *args, **kwargs):
        """Calls the given callback on the next I/O loop iteration.

        Safe for use from a Python signal handler; should not be used
        otherwise.

        Callbacks added with this method will be run without any
        `.stack_context`, to avoid picking up the context of the function
        that was interrupted by the signal.
        """
        raise NotImplementedError()

    def spawn_callback(self, callback, *args, **kwargs):
        """Calls the given callback on the next IOLoop iteration.

        Unlike all other callback-related methods on IOLoop,
        ``spawn_callback`` does not associate the callback with its caller's
        ``stack_context``, so it is suitable for fire-and-forget callbacks
        that should not interfere with the caller.

        .. versionadded:: 4.0
        """
        with stack_context.NullContext():
            self.add_callback(callback, *args, **kwargs)

    def add_future(self, future, callback):
        """Schedules a callback on the ``IOLoop`` when the given
        `.Future` is finished.

        The callback is invoked with one argument, the
        `.Future`.
        """
        assert is_future(future)
        callback = stack_context.wrap(callback)
        future_add_done_callback(
            future, lambda future: self.add_callback(callback, future))

    def run_in_executor(self, executor, func, *args):
        """Runs a function in a ``concurrent.futures.Executor``. If
        ``executor`` is ``None``, the IO loop's default executor will be used.

        Use `functools.partial` to pass keyword arguments to ``func``.

        .. versionadded:: 5.0
        """
        if ThreadPoolExecutor is None:
            raise RuntimeError(
                "concurrent.futures is required to use IOLoop.run_in_executor")

        if executor is None:
            if not hasattr(self, '_executor'):
                from tornado.process import cpu_count
                self._executor = ThreadPoolExecutor(max_workers=(cpu_count() * 5))
            executor = self._executor
        c_future = executor.submit(func, *args)
        # Concurrent Futures are not usable with await. Wrap this in a
        # Tornado Future instead, using self.add_future for thread-safety.
        t_future = Future()
        self.add_future(c_future, lambda f: chain_future(f, t_future))
        return t_future

    def set_default_executor(self, executor):
        """Sets the default executor to use with :meth:`run_in_executor`.

        .. versionadded:: 5.0
        """
        self._executor = executor

    def _run_callback(self, callback):
        """Runs a callback with error handling.

        For use in subclasses.
        """
        try:
            ret = callback()
            if ret is not None:
                from tornado import gen
                # Functions that return Futures typically swallow all
                # exceptions and store them in the Future.  If a Future
                # makes it out to the IOLoop, ensure its exception (if any)
                # gets logged too.
                try:
                    ret = gen.convert_yielded(ret)
                except gen.BadYieldError:
                    # It's not unusual for add_callback to be used with
                    # methods returning a non-None and non-yieldable
                    # result, which should just be ignored.
                    pass
                else:
                    self.add_future(ret, self._discard_future_result)
        except Exception:
            self.handle_callback_exception(callback)

    def _discard_future_result(self, future):
        """Avoid unhandled-exception warnings from spawned coroutines."""
        future.result()

    def handle_callback_exception(self, callback):
        """This method is called whenever a callback run by the `IOLoop`
        throws an exception.

        By default simply logs the exception as an error.  Subclasses
        may override this method to customize reporting of exceptions.

        The exception itself is not passed explicitly, but is available
        in `sys.exc_info`.
        """
        app_log.error("Exception in callback %r", callback, exc_info=True)

    def split_fd(self, fd):
        """Returns an (fd, obj) pair from an ``fd`` parameter.

        We accept both raw file descriptors and file-like objects as
        input to `add_handler` and related methods.  When a file-like
        object is passed, we must retain the object itself so we can
        close it correctly when the `IOLoop` shuts down, but the
        poller interfaces favor file descriptors (they will accept
        file-like objects and call ``fileno()`` for you, but they
        always return the descriptor itself).

        This method is provided for use by `IOLoop` subclasses and should
        not generally be used by application code.

        .. versionadded:: 4.0
        """
        try:
            return fd.fileno(), fd
        except AttributeError:
            return fd, fd

    def close_fd(self, fd):
        """Utility method to close an ``fd``.

        If ``fd`` is a file-like object, we close it directly; otherwise
        we use `os.close`.

        This method is provided for use by `IOLoop` subclasses (in
        implementations of ``IOLoop.close(all_fds=True)`` and should
        not generally be used by application code.

        .. versionadded:: 4.0
        """
        try:
            try:
                fd.close()
            except AttributeError:
                os.close(fd)
        except OSError:
            pass


class PollIOLoop(IOLoop):
    """Base class for IOLoops built around a select-like function.

    For concrete implementations, see `tornado.platform.epoll.EPollIOLoop`
    (Linux), `tornado.platform.kqueue.KQueueIOLoop` (BSD and Mac), or
    `tornado.platform.select.SelectIOLoop` (all platforms).
    """
    def initialize(self, impl, time_func=None, **kwargs):
        super(PollIOLoop, self).initialize(**kwargs)
        self._impl = impl
        if hasattr(self._impl, 'fileno'):
            set_close_exec(self._impl.fileno())
        self.time_func = time_func or time.time
        self._handlers = {}
        self._events = {}
        self._callbacks = collections.deque()
        self._timeouts = []
        self._cancellations = 0
        self._running = False
        self._stopped = False
        self._closing = False
        self._thread_ident = None
        self._pid = os.getpid()
        self._blocking_signal_threshold = None
        self._timeout_counter = itertools.count()

        # Create a pipe that we send bogus data to when we want to wake
        # the I/O loop when it is idle
        self._waker = Waker()
        self.add_handler(self._waker.fileno(),
                         lambda fd, events: self._waker.consume(),
                         self.READ)

    @classmethod
    def configurable_base(cls):
        return PollIOLoop

    @classmethod
    def configurable_default(cls):
        if hasattr(select, "epoll"):
            from tornado.platform.epoll import EPollIOLoop
            return EPollIOLoop
        if hasattr(select, "kqueue"):
            # Python 2.6+ on BSD or Mac
            from tornado.platform.kqueue import KQueueIOLoop
            return KQueueIOLoop
        from tornado.platform.select import SelectIOLoop
        return SelectIOLoop

    def close(self, all_fds=False):
        self._closing = True
        self.remove_handler(self._waker.fileno())
        if all_fds:
            for fd, handler in list(self._handlers.values()):
                self.close_fd(fd)
        self._waker.close()
        self._impl.close()
        self._callbacks = None
        self._timeouts = None
        if hasattr(self, '_executor'):
            self._executor.shutdown()

    def add_handler(self, fd, handler, events):
        fd, obj = self.split_fd(fd)
        self._handlers[fd] = (obj, stack_context.wrap(handler))
        self._impl.register(fd, events | self.ERROR)

    def update_handler(self, fd, events):
        fd, obj = self.split_fd(fd)
        self._impl.modify(fd, events | self.ERROR)

    def remove_handler(self, fd):
        fd, obj = self.split_fd(fd)
        self._handlers.pop(fd, None)
        self._events.pop(fd, None)
        try:
            self._impl.unregister(fd)
        except Exception:
            gen_log.debug("Error deleting fd from IOLoop", exc_info=True)

    def set_blocking_signal_threshold(self, seconds, action):
        if not hasattr(signal, "setitimer"):
            gen_log.error("set_blocking_signal_threshold requires a signal module "
                          "with the setitimer method")
            return
        self._blocking_signal_threshold = seconds
        if seconds is not None:
            signal.signal(signal.SIGALRM,
                          action if action is not None else signal.SIG_DFL)

    def start(self):
        if self._running:
            raise RuntimeError("IOLoop is already running")
        if os.getpid() != self._pid:
            raise RuntimeError("Cannot share PollIOLoops across processes")
        self._setup_logging()
        if self._stopped:
            self._stopped = False
            return
        old_current = IOLoop.current(instance=False)
        if old_current is not self:
            self.make_current()
        self._thread_ident = thread.get_ident()
        self._running = True

        # signal.set_wakeup_fd closes a race condition in event loops:
        # a signal may arrive at the beginning of select/poll/etc
        # before it goes into its interruptible sleep, so the signal
        # will be consumed without waking the select.  The solution is
        # for the (C, synchronous) signal handler to write to a pipe,
        # which will then be seen by select.
        #
        # In python's signal handling semantics, this only matters on the
        # main thread (fortunately, set_wakeup_fd only works on the main
        # thread and will raise a ValueError otherwise).
        #
        # If someone has already set a wakeup fd, we don't want to
        # disturb it.  This is an issue for twisted, which does its
        # SIGCHLD processing in response to its own wakeup fd being
        # written to.  As long as the wakeup fd is registered on the IOLoop,
        # the loop will still wake up and everything should work.
        old_wakeup_fd = None
        if hasattr(signal, 'set_wakeup_fd') and os.name == 'posix':
            # requires python 2.6+, unix.  set_wakeup_fd exists but crashes
            # the python process on windows.
            try:
                old_wakeup_fd = signal.set_wakeup_fd(self._waker.write_fileno())
                if old_wakeup_fd != -1:
                    # Already set, restore previous value.  This is a little racy,
                    # but there's no clean get_wakeup_fd and in real use the
                    # IOLoop is just started once at the beginning.
                    signal.set_wakeup_fd(old_wakeup_fd)
                    old_wakeup_fd = None
            except ValueError:
                # Non-main thread, or the previous value of wakeup_fd
                # is no longer valid.
                old_wakeup_fd = None

        try:
            while True:
                # Prevent IO event starvation by delaying new callbacks
                # to the next iteration of the event loop.
                ncallbacks = len(self._callbacks)

                # Add any timeouts that have come due to the callback list.
                # Do not run anything until we have determined which ones
                # are ready, so timeouts that call add_timeout cannot
                # schedule anything in this iteration.
                due_timeouts = []
                if self._timeouts:
                    now = self.time()
                    while self._timeouts:
                        if self._timeouts[0].callback is None:
                            # The timeout was cancelled.  Note that the
                            # cancellation check is repeated below for timeouts
                            # that are cancelled by another timeout or callback.
                            heapq.heappop(self._timeouts)
                            self._cancellations -= 1
                        elif self._timeouts[0].deadline <= now:
                            due_timeouts.append(heapq.heappop(self._timeouts))
                        else:
                            break
                    if (self._cancellations > 512 and
                            self._cancellations > (len(self._timeouts) >> 1)):
                        # Clean up the timeout queue when it gets large and it's
                        # more than half cancellations.
                        self._cancellations = 0
                        self._timeouts = [x for x in self._timeouts
                                          if x.callback is not None]
                        heapq.heapify(self._timeouts)

                for i in range(ncallbacks):
                    self._run_callback(self._callbacks.popleft())
                for timeout in due_timeouts:
                    if timeout.callback is not None:
                        self._run_callback(timeout.callback)
                # Closures may be holding on to a lot of memory, so allow
                # them to be freed before we go into our poll wait.
                due_timeouts = timeout = None

                if self._callbacks:
                    # If any callbacks or timeouts called add_callback,
                    # we don't want to wait in poll() before we run them.
                    poll_timeout = 0.0
                elif self._timeouts:
                    # If there are any timeouts, schedule the first one.
                    # Use self.time() instead of 'now' to account for time
                    # spent running callbacks.
                    poll_timeout = self._timeouts[0].deadline - self.time()
                    poll_timeout = max(0, min(poll_timeout, _POLL_TIMEOUT))
                else:
                    # No timeouts and no callbacks, so use the default.
                    poll_timeout = _POLL_TIMEOUT

                if not self._running:
                    break

                if self._blocking_signal_threshold is not None:
                    # clear alarm so it doesn't fire while poll is waiting for
                    # events.
                    signal.setitimer(signal.ITIMER_REAL, 0, 0)

                try:
                    event_pairs = self._impl.poll(poll_timeout)
                except Exception as e:
                    # Depending on python version and IOLoop implementation,
                    # different exception types may be thrown and there are
                    # two ways EINTR might be signaled:
                    # * e.errno == errno.EINTR
                    # * e.args is like (errno.EINTR, 'Interrupted system call')
                    if errno_from_exception(e) == errno.EINTR:
                        continue
                    else:
                        raise

                if self._blocking_signal_threshold is not None:
                    signal.setitimer(signal.ITIMER_REAL,
                                     self._blocking_signal_threshold, 0)

                # Pop one fd at a time from the set of pending fds and run
                # its handler. Since that handler may perform actions on
                # other file descriptors, there may be reentrant calls to
                # this IOLoop that modify self._events
                self._events.update(event_pairs)
                while self._events:
                    fd, events = self._events.popitem()
                    try:
                        fd_obj, handler_func = self._handlers[fd]
                        handler_func(fd_obj, events)
                    except (OSError, IOError) as e:
                        if errno_from_exception(e) == errno.EPIPE:
                            # Happens when the client closes the connection
                            pass
                        else:
                            self.handle_callback_exception(self._handlers.get(fd))
                    except Exception:
                        self.handle_callback_exception(self._handlers.get(fd))
                fd_obj = handler_func = None

        finally:
            # reset the stopped flag so another start/stop pair can be issued
            self._stopped = False
            if self._blocking_signal_threshold is not None:
                signal.setitimer(signal.ITIMER_REAL, 0, 0)
            if old_current is None:
                IOLoop.clear_current()
            elif old_current is not self:
                old_current.make_current()
            if old_wakeup_fd is not None:
                signal.set_wakeup_fd(old_wakeup_fd)

    def stop(self):
        self._running = False
        self._stopped = True
        self._waker.wake()

    def time(self):
        return self.time_func()

    def call_at(self, deadline, callback, *args, **kwargs):
        timeout = _Timeout(
            deadline,
            functools.partial(stack_context.wrap(callback), *args, **kwargs),
            self)
        heapq.heappush(self._timeouts, timeout)
        return timeout

    def remove_timeout(self, timeout):
        # Removing from a heap is complicated, so just leave the defunct
        # timeout object in the queue (see discussion in
        # http://docs.python.org/library/heapq.html).
        # If this turns out to be a problem, we could add a garbage
        # collection pass whenever there are too many dead timeouts.
        timeout.callback = None
        self._cancellations += 1

    def add_callback(self, callback, *args, **kwargs):
        if self._closing:
            return
        # Blindly insert into self._callbacks. This is safe even
        # from signal handlers because deque.append is atomic.
        self._callbacks.append(functools.partial(
            stack_context.wrap(callback), *args, **kwargs))
        if thread.get_ident() != self._thread_ident:
            # This will write one byte but Waker.consume() reads many
            # at once, so it's ok to write even when not strictly
            # necessary.
            self._waker.wake()
        else:
            # If we're on the IOLoop's thread, we don't need to wake anyone.
            pass

    def add_callback_from_signal(self, callback, *args, **kwargs):
        with stack_context.NullContext():
            self.add_callback(callback, *args, **kwargs)


class _Timeout(object):
    """An IOLoop timeout, a UNIX timestamp and a callback"""

    # Reduce memory overhead when there are lots of pending callbacks
    __slots__ = ['deadline', 'callback', 'tdeadline']

    def __init__(self, deadline, callback, io_loop):
        if not isinstance(deadline, numbers.Real):
            raise TypeError("Unsupported deadline %r" % deadline)
        self.deadline = deadline
        self.callback = callback
        self.tdeadline = (deadline, next(io_loop._timeout_counter))

    # Comparison methods to sort by deadline, with object id as a tiebreaker
    # to guarantee a consistent ordering.  The heapq module uses __le__
    # in python2.5, and __lt__ in 2.6+ (sort() and most other comparisons
    # use __lt__).
    def __lt__(self, other):
        return self.tdeadline < other.tdeadline

    def __le__(self, other):
        return self.tdeadline <= other.tdeadline


class PeriodicCallback(object):
    """Schedules the given callback to be called periodically.

    The callback is called every ``callback_time`` milliseconds.
    Note that the timeout is given in milliseconds, while most other
    time-related functions in Tornado use seconds.

    If the callback runs for longer than ``callback_time`` milliseconds,
    subsequent invocations will be skipped to get back on schedule.

    `start` must be called after the `PeriodicCallback` is created.

    .. versionchanged:: 5.0
       The ``io_loop`` argument (deprecated since version 4.1) has been removed.
    """
    def __init__(self, callback, callback_time):
        self.callback = callback
        if callback_time <= 0:
            raise ValueError("Periodic callback must have a positive callback_time")
        self.callback_time = callback_time
        self._running = False
        self._timeout = None

    def start(self):
        """Starts the timer."""
        # Looking up the IOLoop here allows to first instantiate the
        # PeriodicCallback in another thread, then start it using
        # IOLoop.add_callback().
        self.io_loop = IOLoop.current()
        self._running = True
        self._next_timeout = self.io_loop.time()
        self._schedule_next()

    def stop(self):
        """Stops the timer."""
        self._running = False
        if self._timeout is not None:
            self.io_loop.remove_timeout(self._timeout)
            self._timeout = None

    def is_running(self):
        """Return True if this `.PeriodicCallback` has been started.

        .. versionadded:: 4.1
        """
        return self._running

    def _run(self):
        if not self._running:
            return
        try:
            return self.callback()
        except Exception:
            self.io_loop.handle_callback_exception(self.callback)
        finally:
            self._schedule_next()

    def _schedule_next(self):
        if self._running:
            current_time = self.io_loop.time()

            if self._next_timeout <= current_time:
                callback_time_sec = self.callback_time / 1000.0
                self._next_timeout += (math.floor((current_time - self._next_timeout) /
                                                  callback_time_sec) + 1) * callback_time_sec

            self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run)

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
user