{
    "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\nIn Tornado 6.0, `.IOLoop` is a wrapper around the `asyncio` event\nloop, with a slightly different interface for historical reasons.\nApplications can use either the `.IOLoop` interface or the underlying\n`asyncio` event loop directly (unless compatibility with older\nversions of Tornado is desired, in which case `.IOLoop` must be used).\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\n\"\"\"\n\nimport asyncio\nimport concurrent.futures\nimport datetime\nimport functools\nimport logging\nimport numbers\nimport os\nimport sys\nimport time\nimport math\nimport random\n\nfrom tornado.concurrent import (\n    Future,\n    is_future,\n    chain_future,\n    future_set_exc_info,\n    future_add_done_callback,\n)\nfrom tornado.log import app_log\nfrom tornado.util import Configurable, TimeoutError, import_object\n\nimport typing\nfrom typing import Union, Any, Type, Optional, Callable, TypeVar, Tuple, Awaitable\n\nif typing.TYPE_CHECKING:\n    from typing import Dict, List  # noqa: F401\n\n    from typing_extensions import Protocol\nelse:\n    Protocol = object\n\n\nclass _Selectable(Protocol):\n    def fileno(self) -> int:\n        pass\n\n    def close(self) -> None:\n        pass\n\n\n_T = TypeVar(\"_T\")\n_S = TypeVar(\"_S\", bound=_Selectable)\n\n\nclass IOLoop(Configurable):\n    \"\"\"An I/O event loop.\n\n    As of Tornado 6.0, `IOLoop` is a wrapper around the `asyncio` event\n    loop.\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.iostream import IOStream\n\n        async def handle_connection(connection, address):\n            stream = IOStream(connection)\n            message = await 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 BlockingIOError:\n                    return\n                connection.setblocking(0)\n                io_loop = tornado.ioloop.IOLoop.current()\n                io_loop.spawn_callback(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\n    # These constants were originally based on constants from the epoll module.\n    NONE = 0\n    READ = 0x001\n    WRITE = 0x004\n    ERROR = 0x018\n\n    # In Python 3, _ioloop_for_asyncio maps from asyncio loops to IOLoops.\n    _ioloop_for_asyncio = dict()  # type: Dict[asyncio.AbstractEventLoop, IOLoop]\n\n    @classmethod\n    def configure(\n        cls, impl: \"Union[None, str, Type[Configurable]]\", **kwargs: Any\n    ) -> None:\n        if asyncio is not None:\n            from tornado.platform.asyncio import BaseAsyncIOLoop\n\n            if isinstance(impl, str):\n                impl = import_object(impl)\n            if isinstance(impl, type) and not issubclass(impl, BaseAsyncIOLoop):\n                raise RuntimeError(\n                    \"only AsyncIOLoop is allowed when asyncio is available\"\n                )\n        super(IOLoop, cls).configure(impl, **kwargs)\n\n    @staticmethod\n    def instance() -> \"IOLoop\":\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) -> None:\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() -> None:\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    @typing.overload\n    @staticmethod\n    def current() -> \"IOLoop\":\n        pass\n\n    @typing.overload\n    @staticmethod\n    def current(instance: bool = True) -> Optional[\"IOLoop\"]:  # noqa: F811\n        pass\n\n    @staticmethod\n    def current(instance: bool = True) -> Optional[\"IOLoop\"]:  # noqa: F811\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        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\n                current = AsyncIOMainLoop(make_current=True)  # type: Optional[IOLoop]\n            else:\n                current = None\n        return current\n\n    def make_current(self) -> None:\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        raise NotImplementedError()\n\n    @staticmethod\n    def clear_current() -> None:\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) -> None:\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) -> Type[Configurable]:\n        return IOLoop\n\n    @classmethod\n    def configurable_default(cls) -> Type[Configurable]:\n        from tornado.platform.asyncio import AsyncIOLoop\n\n        return AsyncIOLoop\n\n    def initialize(self, make_current: Optional[bool] = None) -> 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: bool = False) -> None:\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    @typing.overload\n    def add_handler(\n        self, fd: int, handler: Callable[[int, int], None], events: int\n    ) -> None:\n        pass\n\n    @typing.overload  # noqa: F811\n    def add_handler(\n        self, fd: _S, handler: Callable[[_S, int], None], events: int\n    ) -> None:\n        pass\n\n    def add_handler(  # noqa: F811\n        self, fd: Union[int, _Selectable], handler: Callable[..., None], events: int\n    ) -> None:\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()`` and ``close()`` method.\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: Union[int, _Selectable], events: int) -> None:\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: Union[int, _Selectable]) -> None:\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 start(self) -> None:\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) -> None:\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(\n            [\n                logging.getLogger().handlers,\n                logging.getLogger(\"tornado\").handlers,\n                logging.getLogger(\"tornado.application\").handlers,\n            ]\n        ):\n            logging.basicConfig()\n\n    def stop(self) -> None:\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        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: Callable, timeout: Optional[float] = None) -> Any:\n        \"\"\"Starts the `IOLoop`, runs the given function, and stops the loop.\n\n        The function must return either an awaitable object or\n        ``None``. If the function returns an awaitable object, the\n        `IOLoop` will run until the awaitable is resolved (and\n        `run_sync()` will return the awaitable'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 to allow asynchronous calls in a\n        ``main()`` function::\n\n            async 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-awaitable value is now an error.\n\n        .. versionchanged:: 5.0\n           If a timeout occurs, the ``func`` coroutine will be cancelled.\n\n        \"\"\"\n        future_cell = [None]  # type: List[Optional[Future]]\n\n        def run() -> None:\n            try:\n                result = func()\n                if result is not None:\n                    from tornado.gen import convert_yielded\n\n                    result = convert_yielded(result)\n            except Exception:\n                fut = Future()  # type: Future[Any]\n                future_cell[0] = fut\n                future_set_exc_info(fut, sys.exc_info())\n            else:\n                if is_future(result):\n                    future_cell[0] = result\n                else:\n                    fut = Future()\n                    future_cell[0] = fut\n                    fut.set_result(result)\n            assert future_cell[0] is not None\n            self.add_future(future_cell[0], lambda future: self.stop())\n\n        self.add_callback(run)\n        if timeout is not None:\n\n            def timeout_callback() -> None:\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                assert future_cell[0] is not None\n                if not future_cell[0].cancel():\n                    self.stop()\n\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        assert future_cell[0] is not None\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) -> float:\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        Historically, the IOLoop could be customized to use e.g.\n        `time.monotonic` instead of `time.time`, but this is not\n        currently supported and so this method is equivalent to\n        `time.time`.\n\n        \"\"\"\n        return time.time()\n\n    def add_timeout(\n        self,\n        deadline: Union[float, datetime.timedelta],\n        callback: Callable[..., None],\n        *args: Any,\n        **kwargs: Any\n    ) -> object:\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(\n                self.time() + deadline.total_seconds(), callback, *args, **kwargs\n            )\n        else:\n            raise TypeError(\"Unsupported deadline %r\" % deadline)\n\n    def call_later(\n        self, delay: float, callback: Callable[..., None], *args: Any, **kwargs: Any\n    ) -> object:\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(\n        self, when: float, callback: Callable[..., None], *args: Any, **kwargs: Any\n    ) -> object:\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: object) -> None:\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: Callable, *args: Any, **kwargs: Any) -> None:\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(\n        self, callback: Callable, *args: Any, **kwargs: Any\n    ) -> None:\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        raise NotImplementedError()\n\n    def spawn_callback(self, callback: Callable, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Calls the given callback on the next IOLoop iteration.\n\n        As of Tornado 6.0, this method is equivalent to `add_callback`.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        self.add_callback(callback, *args, **kwargs)\n\n    def add_future(\n        self,\n        future: \"Union[Future[_T], concurrent.futures.Future[_T]]\",\n        callback: Callable[[\"Future[_T]\"], None],\n    ) -> None:\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        This method only accepts `.Future` objects and not other\n        awaitables (unlike most of Tornado where the two are\n        interchangeable).\n        \"\"\"\n        if isinstance(future, Future):\n            # Note that we specifically do not want the inline behavior of\n            # tornado.concurrent.future_add_done_callback. We always want\n            # this callback scheduled on the next IOLoop iteration (which\n            # asyncio.Future always does).\n            #\n            # Wrap the callback in self._run_callback so we control\n            # the error logging (i.e. it goes to tornado.log.app_log\n            # instead of asyncio's log).\n            future.add_done_callback(\n                lambda f: self._run_callback(functools.partial(callback, future))\n            )\n        else:\n            assert is_future(future)\n            # For concurrent futures, we use self.add_callback, so\n            # it's fine if future_add_done_callback inlines that call.\n            future_add_done_callback(\n                future, lambda f: self.add_callback(callback, future)\n            )\n\n    def run_in_executor(\n        self,\n        executor: Optional[concurrent.futures.Executor],\n        func: Callable[..., _T],\n        *args: Any\n    ) -> Awaitable[_T]:\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 executor is None:\n            if not hasattr(self, \"_executor\"):\n                from tornado.process import cpu_count\n\n                self._executor = concurrent.futures.ThreadPoolExecutor(\n                    max_workers=(cpu_count() * 5)\n                )  # type: concurrent.futures.Executor\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()  # type: Future[_T]\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: concurrent.futures.Executor) -> None:\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: Callable[[], Any]) -> None:\n        \"\"\"Runs a callback with error handling.\n\n        .. versionchanged:: 6.0\n\n           CancelledErrors are no longer logged.\n        \"\"\"\n        try:\n            ret = callback()\n            if ret is not None:\n                from tornado import gen\n\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 asyncio.CancelledError:\n            pass\n        except Exception:\n            app_log.error(\"Exception in callback %r\", callback, exc_info=True)\n\n    def _discard_future_result(self, future: Future) -> None:\n        \"\"\"Avoid unhandled-exception warnings from spawned coroutines.\"\"\"\n        future.result()\n\n    def split_fd(\n        self, fd: Union[int, _Selectable]\n    ) -> Tuple[int, Union[int, _Selectable]]:\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        if isinstance(fd, int):\n            return fd, fd\n        return fd.fileno(), fd\n\n    def close_fd(self, fd: Union[int, _Selectable]) -> None:\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            if isinstance(fd, int):\n                os.close(fd)\n            else:\n                fd.close()\n        except OSError:\n            pass\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__(\n        self, deadline: float, callback: Callable[[], None], io_loop: IOLoop\n    ) -> None:\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 = (\n            deadline,\n            next(io_loop._timeout_counter),\n        )  # type: Tuple[float, int]\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: \"_Timeout\") -> bool:\n        return self.tdeadline < other.tdeadline\n\n    def __le__(self, other: \"_Timeout\") -> bool:\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 ``jitter`` is specified, each callback time will be randomly selected\n    within a window of ``jitter * callback_time`` milliseconds.\n    Jitter can be used to reduce alignment of events with similar periods.\n    A jitter of 0.1 means allowing a 10% variation in callback time.\n    The window is centered on ``callback_time`` so the total number of calls\n    within a given interval should not be significantly affected by adding\n    jitter.\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    .. versionchanged:: 5.1\n       The ``jitter`` argument is added.\n    \"\"\"\n\n    def __init__(\n        self, callback: Callable[[], None], callback_time: float, jitter: float = 0\n    ) -> None:\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.jitter = jitter\n        self._running = False\n        self._timeout = None  # type: object\n\n    def start(self) -> None:\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) -> None:\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) -> bool:\n        \"\"\"Returns ``True`` if this `.PeriodicCallback` has been started.\n\n        .. versionadded:: 4.1\n        \"\"\"\n        return self._running\n\n    def _run(self) -> None:\n        if not self._running:\n            return\n        try:\n            return self.callback()\n        except Exception:\n            app_log.error(\"Exception in callback %r\", self.callback, exc_info=True)\n        finally:\n            self._schedule_next()\n\n    def _schedule_next(self) -> None:\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: float) -> None:\n        callback_time_sec = self.callback_time / 1000.0\n        if self.jitter:\n            # apply jitter fraction\n            callback_time_sec *= 1 + (self.jitter * (random.random() - 0.5))\n        if self._next_timeout <= current_time:\n            # The period should be measured from the start of one call\n            # to the start of the next. If one call takes too long,\n            # skip cycles to get back to a multiple of the original\n            # schedule.\n            self._next_timeout += (\n                math.floor((current_time - self._next_timeout) / callback_time_sec) + 1\n            ) * callback_time_sec\n        else:\n            # If the clock moved backwards, ensure we advance the next\n            # timeout instead of recomputing the same value again.\n            # This may result in long gaps between callbacks if the\n            # clock jumps backwards by a lot, but the far more common\n            # scenario is a small NTP adjustment that should just be\n            # ignored.\n            #\n            # Note that on some systems if time.time() runs slower\n            # than time.monotonic() (most common on windows), we\n            # effectively experience a small backwards time jump on\n            # every iteration because PeriodicCallback uses\n            # time.time() while asyncio schedules callbacks using\n            # time.monotonic().\n            # https://github.com/tornadoweb/tornado/issues/2333\n            self._next_timeout += callback_time_sec\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\nIn Tornado 6.0, `.IOLoop` is a wrapper around the `asyncio` event\nloop, with a slightly different interface for historical reasons.\nApplications can use either the `.IOLoop` interface or the underlying\n`asyncio` event loop directly (unless compatibility with older\nversions of Tornado is desired, in which case `.IOLoop` must be used).\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\n\"\"\"\n\nimport asyncio\nimport concurrent.futures\nimport datetime\nimport functools\nimport logging\nimport numbers\nimport os\nimport sys\nimport time\nimport math\nimport random\n\nfrom tornado.concurrent import (\n    Future,\n    is_future,\n    chain_future,\n    future_set_exc_info,\n    future_add_done_callback,\n)\nfrom tornado.log import app_log\nfrom tornado.util import Configurable, TimeoutError, import_object\n\nimport typing\nfrom typing import Union, Any, Type, Optional, Callable, TypeVar, Tuple, Awaitable\n\nif typing.TYPE_CHECKING:\n    from typing import Dict, List  # noqa: F401\n\n    from typing_extensions import Protocol\nelse:\n    Protocol = object\n\n\nclass _Selectable(Protocol):\n    def fileno(self) -> int:\n        pass\n\n    def close(self) -> None:\n        pass\n\n\n_T = TypeVar(\"_T\")\n_S = TypeVar(\"_S\", bound=_Selectable)\n\n\nclass IOLoop(Configurable):\n    \"\"\"An I/O event loop.\n\n    As of Tornado 6.0, `IOLoop` is a wrapper around the `asyncio` event\n    loop.\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.iostream import IOStream\n\n        async def handle_connection(connection, address):\n            stream = IOStream(connection)\n            message = await 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 BlockingIOError:\n                    return\n                connection.setblocking(0)\n                io_loop = tornado.ioloop.IOLoop.current()\n                io_loop.spawn_callback(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\n    # These constants were originally based on constants from the epoll module.\n    NONE = 0\n    READ = 0x001\n    WRITE = 0x004\n    ERROR = 0x018\n\n    # In Python 3, _ioloop_for_asyncio maps from asyncio loops to IOLoops.\n    _ioloop_for_asyncio = dict()  # type: Dict[asyncio.AbstractEventLoop, IOLoop]\n\n    @classmethod\n    def configure(\n        cls, impl: \"Union[None, str, Type[Configurable]]\", **kwargs: Any\n    ) -> None:\n        if asyncio is not None:\n            from tornado.platform.asyncio import BaseAsyncIOLoop\n\n            if isinstance(impl, str):\n                impl = import_object(impl)\n            if isinstance(impl, type) and not issubclass(impl, BaseAsyncIOLoop):\n                raise RuntimeError(\n                    \"only AsyncIOLoop is allowed when asyncio is available\"\n                )\n        super(IOLoop, cls).configure(impl, **kwargs)\n\n    @staticmethod\n    def instance() -> \"IOLoop\":\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) -> None:\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() -> None:\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    @typing.overload\n    @staticmethod\n    def current() -> \"IOLoop\":\n        pass\n\n    @typing.overload\n    @staticmethod\n    def current(instance: bool = True) -> Optional[\"IOLoop\"]:  # noqa: F811\n        pass\n\n    @staticmethod\n    def current(instance: bool = True) -> Optional[\"IOLoop\"]:  # noqa: F811\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        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\n                current = AsyncIOMainLoop(make_current=True)  # type: Optional[IOLoop]\n            else:\n                current = None\n        return current\n\n    def make_current(self) -> None:\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        raise NotImplementedError()\n\n    @staticmethod\n    def clear_current() -> None:\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) -> None:\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) -> Type[Configurable]:\n        return IOLoop\n\n    @classmethod\n    def configurable_default(cls) -> Type[Configurable]:\n        from tornado.platform.asyncio import AsyncIOLoop\n\n        return AsyncIOLoop\n\n    def initialize(self, make_current: Optional[bool] = None) -> 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: bool = False) -> None:\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    @typing.overload\n    def add_handler(\n        self, fd: int, handler: Callable[[int, int], None], events: int\n    ) -> None:\n        pass\n\n    @typing.overload  # noqa: F811\n    def add_handler(\n        self, fd: _S, handler: Callable[[_S, int], None], events: int\n    ) -> None:\n        pass\n\n    def add_handler(  # noqa: F811\n        self, fd: Union[int, _Selectable], handler: Callable[..., None], events: int\n    ) -> None:\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()`` and ``close()`` method.\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: Union[int, _Selectable], events: int) -> None:\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: Union[int, _Selectable]) -> None:\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 start(self) -> None:\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) -> None:\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(\n            [\n                logging.getLogger().handlers,\n                logging.getLogger(\"tornado\").handlers,\n                logging.getLogger(\"tornado.application\").handlers,\n            ]\n        ):\n            logging.basicConfig()\n\n    def stop(self) -> None:\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        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: Callable, timeout: Optional[float] = None) -> Any:\n        \"\"\"Starts the `IOLoop`, runs the given function, and stops the loop.\n\n        The function must return either an awaitable object or\n        ``None``. If the function returns an awaitable object, the\n        `IOLoop` will run until the awaitable is resolved (and\n        `run_sync()` will return the awaitable'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 to allow asynchronous calls in a\n        ``main()`` function::\n\n            async 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-awaitable value is now an error.\n\n        .. versionchanged:: 5.0\n           If a timeout occurs, the ``func`` coroutine will be cancelled.\n\n        \"\"\"\n        future_cell = [None]  # type: List[Optional[Future]]\n\n        def run() -> None:\n            try:\n                result = func()\n                if result is not None:\n                    from tornado.gen import convert_yielded\n\n                    result = convert_yielded(result)\n            except Exception:\n                fut = Future()  # type: Future[Any]\n                future_cell[0] = fut\n                future_set_exc_info(fut, sys.exc_info())\n            else:\n                if is_future(result):\n                    future_cell[0] = result\n                else:\n                    fut = Future()\n                    future_cell[0] = fut\n                    fut.set_result(result)\n            assert future_cell[0] is not None\n            self.add_future(future_cell[0], lambda future: self.stop())\n\n        self.add_callback(run)\n        if timeout is not None:\n\n            def timeout_callback() -> None:\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                assert future_cell[0] is not None\n                if not future_cell[0].cancel():\n                    self.stop()\n\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        assert future_cell[0] is not None\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) -> float:\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        Historically, the IOLoop could be customized to use e.g.\n        `time.monotonic` instead of `time.time`, but this is not\n        currently supported and so this method is equivalent to\n        `time.time`.\n\n        \"\"\"\n        return time.time()\n\n    def add_timeout(\n        self,\n        deadline: Union[float, datetime.timedelta],\n        callback: Callable[..., None],\n        *args: Any,\n        **kwargs: Any\n    ) -> object:\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(\n                self.time() + deadline.total_seconds(), callback, *args, **kwargs\n            )\n        else:\n            raise TypeError(\"Unsupported deadline %r\" % deadline)\n\n    def call_later(\n        self, delay: float, callback: Callable[..., None], *args: Any, **kwargs: Any\n    ) -> object:\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(\n        self, when: float, callback: Callable[..., None], *args: Any, **kwargs: Any\n    ) -> object:\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: object) -> None:\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: Callable, *args: Any, **kwargs: Any) -> None:\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(\n        self, callback: Callable, *args: Any, **kwargs: Any\n    ) -> None:\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        raise NotImplementedError()\n\n    def spawn_callback(self, callback: Callable, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Calls the given callback on the next IOLoop iteration.\n\n        As of Tornado 6.0, this method is equivalent to `add_callback`.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        self.add_callback(callback, *args, **kwargs)\n\n    def add_future(\n        self,\n        future: \"Union[Future[_T], concurrent.futures.Future[_T]]\",\n        callback: Callable[[\"Future[_T]\"], None],\n    ) -> None:\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        This method only accepts `.Future` objects and not other\n        awaitables (unlike most of Tornado where the two are\n        interchangeable).\n        \"\"\"\n        if isinstance(future, Future):\n            # Note that we specifically do not want the inline behavior of\n            # tornado.concurrent.future_add_done_callback. We always want\n            # this callback scheduled on the next IOLoop iteration (which\n            # asyncio.Future always does).\n            #\n            # Wrap the callback in self._run_callback so we control\n            # the error logging (i.e. it goes to tornado.log.app_log\n            # instead of asyncio's log).\n            future.add_done_callback(\n                lambda f: self._run_callback(functools.partial(callback, future))\n            )\n        else:\n            assert is_future(future)\n            # For concurrent futures, we use self.add_callback, so\n            # it's fine if future_add_done_callback inlines that call.\n            future_add_done_callback(\n                future, lambda f: self.add_callback(callback, future)\n            )\n\n    def run_in_executor(\n        self,\n        executor: Optional[concurrent.futures.Executor],\n        func: Callable[..., _T],\n        *args: Any\n    ) -> Awaitable[_T]:\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 executor is None:\n            if not hasattr(self, \"_executor\"):\n                from tornado.process import cpu_count\n\n                self._executor = concurrent.futures.ThreadPoolExecutor(\n                    max_workers=(cpu_count() * 5)\n                )  # type: concurrent.futures.Executor\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()  # type: Future[_T]\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: concurrent.futures.Executor) -> None:\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: Callable[[], Any]) -> None:\n        \"\"\"Runs a callback with error handling.\n\n        .. versionchanged:: 6.0\n\n           CancelledErrors are no longer logged.\n        \"\"\"\n        try:\n            ret = callback()\n            if ret is not None:\n                from tornado import gen\n\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 asyncio.CancelledError:\n            pass\n        except Exception:\n            app_log.error(\"Exception in callback %r\", callback, exc_info=True)\n\n    def _discard_future_result(self, future: Future) -> None:\n        \"\"\"Avoid unhandled-exception warnings from spawned coroutines.\"\"\"\n        future.result()\n\n    def split_fd(\n        self, fd: Union[int, _Selectable]\n    ) -> Tuple[int, Union[int, _Selectable]]:\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        if isinstance(fd, int):\n            return fd, fd\n        return fd.fileno(), fd\n\n    def close_fd(self, fd: Union[int, _Selectable]) -> None:\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            if isinstance(fd, int):\n                os.close(fd)\n            else:\n                fd.close()\n        except OSError:\n            pass\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__(\n        self, deadline: float, callback: Callable[[], None], io_loop: IOLoop\n    ) -> None:\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 = (\n            deadline,\n            next(io_loop._timeout_counter),\n        )  # type: Tuple[float, int]\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: \"_Timeout\") -> bool:\n        return self.tdeadline < other.tdeadline\n\n    def __le__(self, other: \"_Timeout\") -> bool:\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 ``jitter`` is specified, each callback time will be randomly selected\n    within a window of ``jitter * callback_time`` milliseconds.\n    Jitter can be used to reduce alignment of events with similar periods.\n    A jitter of 0.1 means allowing a 10% variation in callback time.\n    The window is centered on ``callback_time`` so the total number of calls\n    within a given interval should not be significantly affected by adding\n    jitter.\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    .. versionchanged:: 5.1\n       The ``jitter`` argument is added.\n    \"\"\"\n\n    def __init__(\n        self,\n        callback: Callable[[], None],\n        callback_time: Union[datetime.timedelta, float],\n        jitter: float = 0,\n    ) -> None:\n        self.callback = callback\n        if isinstance(callback_time, datetime.timedelta):\n            self.callback_time = callback_time / datetime.timedelta(milliseconds=1)\n        else:\n            if callback_time <= 0:\n                raise ValueError(\"Periodic callback must have a positive callback_time\")\n            self.callback_time = callback_time\n        self.jitter = jitter\n        self._running = False\n        self._timeout = None  # type: object\n\n    def start(self) -> None:\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) -> None:\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) -> bool:\n        \"\"\"Returns ``True`` if this `.PeriodicCallback` has been started.\n\n        .. versionadded:: 4.1\n        \"\"\"\n        return self._running\n\n    def _run(self) -> None:\n        if not self._running:\n            return\n        try:\n            return self.callback()\n        except Exception:\n            app_log.error(\"Exception in callback %r\", self.callback, exc_info=True)\n        finally:\n            self._schedule_next()\n\n    def _schedule_next(self) -> None:\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: float) -> None:\n        callback_time_sec = self.callback_time / 1000.0\n        if self.jitter:\n            # apply jitter fraction\n            callback_time_sec *= 1 + (self.jitter * (random.random() - 0.5))\n        if self._next_timeout <= current_time:\n            # The period should be measured from the start of one call\n            # to the start of the next. If one call takes too long,\n            # skip cycles to get back to a multiple of the original\n            # schedule.\n            self._next_timeout += (\n                math.floor((current_time - self._next_timeout) / callback_time_sec) + 1\n            ) * callback_time_sec\n        else:\n            # If the clock moved backwards, ensure we advance the next\n            # timeout instead of recomputing the same value again.\n            # This may result in long gaps between callbacks if the\n            # clock jumps backwards by a lot, but the far more common\n            # scenario is a small NTP adjustment that should just be\n            # ignored.\n            #\n            # Note that on some systems if time.time() runs slower\n            # than time.monotonic() (most common on windows), we\n            # effectively experience a small backwards time jump on\n            # every iteration because PeriodicCallback uses\n            # time.time() while asyncio schedules callbacks using\n            # time.monotonic().\n            # https://github.com/tornadoweb/tornado/issues/2333\n            self._next_timeout += callback_time_sec\n",
            "header": {
                "file": {
                    "path": "tornado/ioloop.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "2cf88445",
                "new_commit_hash": "fff29cef",
                "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": 864,
                            "length": 12
                        },
                        "new_range": {
                            "start": 864,
                            "length": 18
                        },
                        "section": "class PeriodicCallback(object):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    \"\"\"",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def __init__(",
                                "type": "context"
                            },
                            {
                                "content": "        self, callback: Callable[[], None], callback_time: float, jitter: float = 0",
                                "type": "deleted"
                            },
                            {
                                "content": "        self,",
                                "type": "added"
                            },
                            {
                                "content": "        callback: Callable[[], None],",
                                "type": "added"
                            },
                            {
                                "content": "        callback_time: Union[datetime.timedelta, float],",
                                "type": "added"
                            },
                            {
                                "content": "        jitter: float = 0,",
                                "type": "added"
                            },
                            {
                                "content": "    ) -> None:",
                                "type": "context"
                            },
                            {
                                "content": "        self.callback = callback",
                                "type": "context"
                            },
                            {
                                "content": "        if callback_time <= 0:",
                                "type": "deleted"
                            },
                            {
                                "content": "            raise ValueError(\"Periodic callback must have a positive callback_time\")",
                                "type": "deleted"
                            },
                            {
                                "content": "        self.callback_time = callback_time",
                                "type": "deleted"
                            },
                            {
                                "content": "        if isinstance(callback_time, datetime.timedelta):",
                                "type": "added"
                            },
                            {
                                "content": "            self.callback_time = callback_time / datetime.timedelta(milliseconds=1)",
                                "type": "added"
                            },
                            {
                                "content": "        else:",
                                "type": "added"
                            },
                            {
                                "content": "            if callback_time <= 0:",
                                "type": "added"
                            },
                            {
                                "content": "                raise ValueError(\"Periodic callback must have a positive callback_time\")",
                                "type": "added"
                            },
                            {
                                "content": "            self.callback_time = callback_time",
                                "type": "added"
                            },
                            {
                                "content": "        self.jitter = jitter",
                                "type": "context"
                            },
                            {
                                "content": "        self._running = False",
                                "type": "context"
                            },
                            {
                                "content": "        self._timeout = None  # type: object",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/ioloop.py",
                            "type": "method",
                            "name": "PeriodicCallback.__init__",
                            "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 ``jitter`` is specified, each callback time will be randomly selected\n    within a window of ``jitter * callback_time`` milliseconds.\n    Jitter can be used to reduce alignment of events with similar periods.\n    A jitter of 0.1 means allowing a 10% variation in callback time.\n    The window is centered on ``callback_time`` so the total number of calls\n    within a given interval should not be significantly affected by adding\n    jitter.\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    .. versionchanged:: 5.1\n       The ``jitter`` argument is added.\n    \"\"\"\n\n    def __init__(\n        self, callback: Callable[[], None], callback_time: float, jitter: float = 0\n    ) -> None:\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.jitter = jitter\n        self._running = False\n        self._timeout = None  # type: object\n\n    def start(self) -> None:\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) -> None:\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) -> bool:\n        \"\"\"Returns ``True`` if this `.PeriodicCallback` has been started.\n\n        .. versionadded:: 4.1\n        \"\"\"\n        return self._running\n\n    def _run(self) -> None:\n        if not self._running:\n            return\n        try:\n            return self.callback()\n        except Exception:\n            app_log.error(\"Exception in callback %r\", self.callback, exc_info=True)\n        finally:\n            self._schedule_next()\n\n    def _schedule_next(self) -> None:\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: float) -> None:\n        callback_time_sec = self.callback_time / 1000.0\n        if self.jitter:\n            # apply jitter fraction\n            callback_time_sec *= 1 + (self.jitter * (random.random() - 0.5))\n        if self._next_timeout <= current_time:\n            # The period should be measured from the start of one call\n            # to the start of the next. If one call takes too long,\n            # skip cycles to get back to a multiple of the original\n            # schedule.\n            self._next_timeout += (\n                math.floor((current_time - self._next_timeout) / callback_time_sec) + 1\n            ) * callback_time_sec\n        else:\n            # If the clock moved backwards, ensure we advance the next\n            # timeout instead of recomputing the same value again.\n            # This may result in long gaps between callbacks if the\n            # clock jumps backwards by a lot, but the far more common\n            # scenario is a small NTP adjustment that should just be\n            # ignored.\n            #\n            # Note that on some systems if time.time() runs slower\n            # than time.monotonic() (most common on windows), we\n            # effectively experience a small backwards time jump on\n            # every iteration because PeriodicCallback uses\n            # time.time() while asyncio schedules callbacks using\n            # time.monotonic().\n            # https://github.com/tornadoweb/tornado/issues/2333\n            self._next_timeout += callback_time_sec",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 866,
                            "end_lineno": 875,
                            "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 ``jitter`` is specified, each callback time will be randomly selected\n    within a window of ``jitter * callback_time`` milliseconds.\n    Jitter can be used to reduce alignment of events with similar periods.\n    A jitter of 0.1 means allowing a 10% variation in callback time.\n    The window is centered on ``callback_time`` so the total number of calls\n    within a given interval should not be significantly affected by adding\n    jitter.\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    .. versionchanged:: 5.1\n       The ``jitter`` argument is added.\n    \"\"\"\n\n    def __init__(\n        self, callback: Callable[[], None], callback_time: float, jitter: float = 0\n    ) -> None:\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.jitter = jitter\n        self._running = False\n        self._timeout = None  # type: object\n\n    def start(self) -> None:\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) -> None:\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) -> bool:\n        \"\"\"Returns ``True`` if this `.PeriodicCallback` has been started.\n\n        .. versionadded:: 4.1\n        \"\"\"\n        return self._running\n\n    def _run(self) -> None:\n        if not self._running:\n            return\n        try:\n            return self.callback()\n        except Exception:\n            app_log.error(\"Exception in callback %r\", self.callback, exc_info=True)\n        finally:\n            self._schedule_next()\n\n    def _schedule_next(self) -> None:\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: float) -> None:\n        callback_time_sec = self.callback_time / 1000.0\n        if self.jitter:\n            # apply jitter fraction\n            callback_time_sec *= 1 + (self.jitter * (random.random() - 0.5))\n        if self._next_timeout <= current_time:\n            # The period should be measured from the start of one call\n            # to the start of the next. If one call takes too long,\n            # skip cycles to get back to a multiple of the original\n            # schedule.\n            self._next_timeout += (\n                math.floor((current_time - self._next_timeout) / callback_time_sec) + 1\n            ) * callback_time_sec\n        else:\n            # If the clock moved backwards, ensure we advance the next\n            # timeout instead of recomputing the same value again.\n            # This may result in long gaps between callbacks if the\n            # clock jumps backwards by a lot, but the far more common\n            # scenario is a small NTP adjustment that should just be\n            # ignored.\n            #\n            # Note that on some systems if time.time() runs slower\n            # than time.monotonic() (most common on windows), we\n            # effectively experience a small backwards time jump on\n            # every iteration because PeriodicCallback uses\n            # time.time() while asyncio schedules callbacks using\n            # time.monotonic().\n            # https://github.com/tornadoweb/tornado/issues/2333\n            self._next_timeout += callback_time_sec",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 839,
                                "end_lineno": 944,
                                "parent": null
                            }
                        },
                        {
                            "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 ``jitter`` is specified, each callback time will be randomly selected\n    within a window of ``jitter * callback_time`` milliseconds.\n    Jitter can be used to reduce alignment of events with similar periods.\n    A jitter of 0.1 means allowing a 10% variation in callback time.\n    The window is centered on ``callback_time`` so the total number of calls\n    within a given interval should not be significantly affected by adding\n    jitter.\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    .. versionchanged:: 5.1\n       The ``jitter`` argument is added.\n    \"\"\"\n\n    def __init__(\n        self, callback: Callable[[], None], callback_time: float, jitter: float = 0\n    ) -> None:\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.jitter = jitter\n        self._running = False\n        self._timeout = None  # type: object\n\n    def start(self) -> None:\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) -> None:\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) -> bool:\n        \"\"\"Returns ``True`` if this `.PeriodicCallback` has been started.\n\n        .. versionadded:: 4.1\n        \"\"\"\n        return self._running\n\n    def _run(self) -> None:\n        if not self._running:\n            return\n        try:\n            return self.callback()\n        except Exception:\n            app_log.error(\"Exception in callback %r\", self.callback, exc_info=True)\n        finally:\n            self._schedule_next()\n\n    def _schedule_next(self) -> None:\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: float) -> None:\n        callback_time_sec = self.callback_time / 1000.0\n        if self.jitter:\n            # apply jitter fraction\n            callback_time_sec *= 1 + (self.jitter * (random.random() - 0.5))\n        if self._next_timeout <= current_time:\n            # The period should be measured from the start of one call\n            # to the start of the next. If one call takes too long,\n            # skip cycles to get back to a multiple of the original\n            # schedule.\n            self._next_timeout += (\n                math.floor((current_time - self._next_timeout) / callback_time_sec) + 1\n            ) * callback_time_sec\n        else:\n            # If the clock moved backwards, ensure we advance the next\n            # timeout instead of recomputing the same value again.\n            # This may result in long gaps between callbacks if the\n            # clock jumps backwards by a lot, but the far more common\n            # scenario is a small NTP adjustment that should just be\n            # ignored.\n            #\n            # Note that on some systems if time.time() runs slower\n            # than time.monotonic() (most common on windows), we\n            # effectively experience a small backwards time jump on\n            # every iteration because PeriodicCallback uses\n            # time.time() while asyncio schedules callbacks using\n            # time.monotonic().\n            # https://github.com/tornadoweb/tornado/issues/2333\n            self._next_timeout += callback_time_sec",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 839,
                            "end_lineno": 944,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "from concurrent.futures import ThreadPoolExecutor\nfrom concurrent import futures\nimport contextlib\nimport datetime\nimport functools\nimport socket\nimport subprocess\nimport sys\nimport threading\nimport time\nimport types\nfrom unittest import mock\nimport unittest\n\nfrom tornado.escape import native_str\nfrom tornado import gen\nfrom tornado.ioloop import IOLoop, TimeoutError, PeriodicCallback\nfrom tornado.log import app_log\nfrom tornado.testing import AsyncTestCase, bind_unused_port, ExpectLog, gen_test\nfrom tornado.test.util import skipIfNonUnix, skipOnTravis\n\nimport typing\n\nif typing.TYPE_CHECKING:\n    from typing import List  # noqa: F401\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)  # type: ignore\n        loop.add_callback(lambda: {})  # type: ignore\n        loop.add_callback(lambda: [])  # type: ignore\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\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\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(\n                sock.fileno(), lambda fd, events: None, IOLoop.READ\n            )\n            # Attempting to add the same handler twice fails\n            # (with a platform-dependent exception)\n            self.assertRaises(\n                Exception,\n                self.io_loop.add_handler,\n                sock.fileno(),\n                lambda fd, events: None,\n                IOLoop.READ,\n            )\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\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    @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\n            def handler(fd, events):\n                self.assertEqual(events, IOLoop.READ)\n                self.stop()\n\n            self.io_loop.add_handler(client.fileno(), handler, IOLoop.READ)\n            self.io_loop.add_timeout(\n                self.io_loop.time() + 0.01, functools.partial(server.send, b\"asdf\")  # type: ignore\n            )\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, 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\n        self.io_loop.add_timeout(now + 0.01, t1)\n\n        def t2():\n            calls[1] = True\n\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 = []  # type: List[int]\n        self.io_loop.add_timeout(self.io_loop.time(), results.append, 1)\n        self.io_loop.add_timeout(datetime.timedelta(seconds=0), 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.\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\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, 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\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, 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\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\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        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\n        @gen.coroutine\n        def callback():\n            self.io_loop.add_callback(self.stop)\n            1 / 0\n\n        self.io_loop.add_callback(callback)\n        with ExpectLog(app_log, \"Exception in callback\"):\n            self.wait()\n\n    def test_exception_logging_native_coro(self):\n        \"\"\"The IOLoop examines exceptions from awaitables and logs them.\"\"\"\n\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        self.io_loop.add_callback(callback)\n        with ExpectLog(app_log, \"Exception in callback\"):\n            self.wait()\n\n    def test_spawn_callback(self):\n        # Both add_callback and spawn_callback run directly on the IOLoop,\n        # so their errors are logged without stopping the test.\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        # 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\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    @skipIfNonUnix\n    @gen_test\n    def test_init_close_race(self):\n        # Regression test for #2367\n        #\n        # Skipped on windows because of what looks like a bug in the\n        # proactor event loop when started and stopped on non-main\n        # threads.\n        def f():\n            for i in range(10):\n                loop = IOLoop()\n                loop.close()\n\n        yield gen.multi([self.io_loop.run_in_executor(None, f) for i in range(2)])\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  # type: typing.Optional[IOLoop]\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\n            def f():\n                self.current_io_loop = IOLoop.current()\n                assert self.io_loop is not None\n                self.io_loop.stop()\n\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 TestIOLoopFutures(AsyncTestCase):\n    def test_add_future_threads(self):\n        with futures.ThreadPoolExecutor(1) as pool:\n\n            def dummy():\n                pass\n\n            self.io_loop.add_future(\n                pool.submit(dummy), lambda future: self.stop(future)\n            )\n            future = self.wait()\n            self.assertTrue(future.done())\n            self.assertTrue(future.result() is None)\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    @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 concurrent future would do that).\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 [async_wrapper(event1, event2), async_wrapper(event2, event1)]\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().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\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\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\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\n        self.assertRaises(TimeoutError, self.io_loop.run_sync, f, timeout=0.01)\n\n    def test_native_coroutine(self):\n        @gen.coroutine\n        def f1():\n            yield gen.moment\n\n        async def f2():\n            await f1()\n\n        self.io_loop.run_sync(f2)\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 (negative values\n        work to simulate clock adjustments during the call, or more or\n        less equivalently, between calls). This method returns the\n        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 dummy(self):\n        pass\n\n    def test_basic(self):\n        pc = PeriodicCallback(self.dummy, 10000)\n        self.assertEqual(\n            self.simulate_calls(pc, [0] * 5), [1010, 1020, 1030, 1040, 1050]\n        )\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,\n            1020,\n            1030,  # first 3 calls on schedule\n            1050,\n            1070,  # next 2 delayed one cycle\n            1100,\n            1130,  # next 2 delayed 2 cycles\n            1170,\n            1210,  # next 2 delayed 3 cycles\n            1220,\n            1230,  # then back on schedule.\n        ]\n\n        pc = PeriodicCallback(self.dummy, 10000)\n        self.assertEqual(self.simulate_calls(pc, call_durations), expected)\n\n    def test_clock_backwards(self):\n        pc = PeriodicCallback(self.dummy, 10000)\n        # Backwards jumps are ignored, potentially resulting in a\n        # slightly slow schedule (although we assume that when\n        # time.time() and time.monotonic() are different, time.time()\n        # is getting adjusted by NTP and is therefore more accurate)\n        self.assertEqual(\n            self.simulate_calls(pc, [-2, -1, -3, -2, 0]), [1010, 1020, 1030, 1040, 1050]\n        )\n\n        # For big jumps, we should perhaps alter the schedule, but we\n        # don't currently. This trace shows that we run callbacks\n        # every 10s of time.time(), but the first and second calls are\n        # 110s of real time apart because the backwards jump is\n        # ignored.\n        self.assertEqual(self.simulate_calls(pc, [-100, 0, 0]), [1010, 1020, 1030])\n\n    def test_jitter(self):\n        random_times = [0.5, 1, 0, 0.75]\n        expected = [1010, 1022.5, 1030, 1041.25]\n        call_durations = [0] * len(random_times)\n        pc = PeriodicCallback(self.dummy, 10000, jitter=0.5)\n\n        def mock_random():\n            return random_times.pop(0)\n\n        with mock.patch(\"random.random\", mock_random):\n            self.assertEqual(self.simulate_calls(pc, call_durations), expected)\n\n\nclass TestIOLoopConfiguration(unittest.TestCase):\n    def run_python(self, *statements):\n        stmt_list = [\n            \"from tornado.ioloop import IOLoop\",\n            \"classname = lambda x: x.__class__.__name__\",\n        ] + list(statements)\n        args = [sys.executable, \"-c\", \"; \".join(stmt_list)]\n        return native_str(subprocess.check_output(args)).strip()\n\n    def test_default(self):\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\n    def test_asyncio(self):\n        cls = self.run_python(\n            'IOLoop.configure(\"tornado.platform.asyncio.AsyncIOLoop\")',\n            \"print(classname(IOLoop.current()))\",\n        )\n        self.assertEqual(cls, \"AsyncIOMainLoop\")\n\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        )\n        self.assertEqual(cls, \"AsyncIOMainLoop\")\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n",
            "new_file_content": "from concurrent.futures import ThreadPoolExecutor\nfrom concurrent import futures\nimport contextlib\nimport datetime\nimport functools\nimport socket\nimport subprocess\nimport sys\nimport threading\nimport time\nimport types\nfrom unittest import mock\nimport unittest\n\nfrom tornado.escape import native_str\nfrom tornado import gen\nfrom tornado.ioloop import IOLoop, TimeoutError, PeriodicCallback\nfrom tornado.log import app_log\nfrom tornado.testing import AsyncTestCase, bind_unused_port, ExpectLog, gen_test\nfrom tornado.test.util import skipIfNonUnix, skipOnTravis\n\nimport typing\n\nif typing.TYPE_CHECKING:\n    from typing import List  # noqa: F401\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)  # type: ignore\n        loop.add_callback(lambda: {})  # type: ignore\n        loop.add_callback(lambda: [])  # type: ignore\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\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\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(\n                sock.fileno(), lambda fd, events: None, IOLoop.READ\n            )\n            # Attempting to add the same handler twice fails\n            # (with a platform-dependent exception)\n            self.assertRaises(\n                Exception,\n                self.io_loop.add_handler,\n                sock.fileno(),\n                lambda fd, events: None,\n                IOLoop.READ,\n            )\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\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    @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\n            def handler(fd, events):\n                self.assertEqual(events, IOLoop.READ)\n                self.stop()\n\n            self.io_loop.add_handler(client.fileno(), handler, IOLoop.READ)\n            self.io_loop.add_timeout(\n                self.io_loop.time() + 0.01, functools.partial(server.send, b\"asdf\")  # type: ignore\n            )\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, 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\n        self.io_loop.add_timeout(now + 0.01, t1)\n\n        def t2():\n            calls[1] = True\n\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 = []  # type: List[int]\n        self.io_loop.add_timeout(self.io_loop.time(), results.append, 1)\n        self.io_loop.add_timeout(datetime.timedelta(seconds=0), 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.\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\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, 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\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, 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\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\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        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\n        @gen.coroutine\n        def callback():\n            self.io_loop.add_callback(self.stop)\n            1 / 0\n\n        self.io_loop.add_callback(callback)\n        with ExpectLog(app_log, \"Exception in callback\"):\n            self.wait()\n\n    def test_exception_logging_native_coro(self):\n        \"\"\"The IOLoop examines exceptions from awaitables and logs them.\"\"\"\n\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        self.io_loop.add_callback(callback)\n        with ExpectLog(app_log, \"Exception in callback\"):\n            self.wait()\n\n    def test_spawn_callback(self):\n        # Both add_callback and spawn_callback run directly on the IOLoop,\n        # so their errors are logged without stopping the test.\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        # 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\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    @skipIfNonUnix\n    @gen_test\n    def test_init_close_race(self):\n        # Regression test for #2367\n        #\n        # Skipped on windows because of what looks like a bug in the\n        # proactor event loop when started and stopped on non-main\n        # threads.\n        def f():\n            for i in range(10):\n                loop = IOLoop()\n                loop.close()\n\n        yield gen.multi([self.io_loop.run_in_executor(None, f) for i in range(2)])\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  # type: typing.Optional[IOLoop]\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\n            def f():\n                self.current_io_loop = IOLoop.current()\n                assert self.io_loop is not None\n                self.io_loop.stop()\n\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 TestIOLoopFutures(AsyncTestCase):\n    def test_add_future_threads(self):\n        with futures.ThreadPoolExecutor(1) as pool:\n\n            def dummy():\n                pass\n\n            self.io_loop.add_future(\n                pool.submit(dummy), lambda future: self.stop(future)\n            )\n            future = self.wait()\n            self.assertTrue(future.done())\n            self.assertTrue(future.result() is None)\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    @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 concurrent future would do that).\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 [async_wrapper(event1, event2), async_wrapper(event2, event1)]\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().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\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\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\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\n        self.assertRaises(TimeoutError, self.io_loop.run_sync, f, timeout=0.01)\n\n    def test_native_coroutine(self):\n        @gen.coroutine\n        def f1():\n            yield gen.moment\n\n        async def f2():\n            await f1()\n\n        self.io_loop.run_sync(f2)\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 (negative values\n        work to simulate clock adjustments during the call, or more or\n        less equivalently, between calls). This method returns the\n        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 dummy(self):\n        pass\n\n    def test_basic(self):\n        pc = PeriodicCallback(self.dummy, 10000)\n        self.assertEqual(\n            self.simulate_calls(pc, [0] * 5), [1010, 1020, 1030, 1040, 1050]\n        )\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,\n            1020,\n            1030,  # first 3 calls on schedule\n            1050,\n            1070,  # next 2 delayed one cycle\n            1100,\n            1130,  # next 2 delayed 2 cycles\n            1170,\n            1210,  # next 2 delayed 3 cycles\n            1220,\n            1230,  # then back on schedule.\n        ]\n\n        pc = PeriodicCallback(self.dummy, 10000)\n        self.assertEqual(self.simulate_calls(pc, call_durations), expected)\n\n    def test_clock_backwards(self):\n        pc = PeriodicCallback(self.dummy, 10000)\n        # Backwards jumps are ignored, potentially resulting in a\n        # slightly slow schedule (although we assume that when\n        # time.time() and time.monotonic() are different, time.time()\n        # is getting adjusted by NTP and is therefore more accurate)\n        self.assertEqual(\n            self.simulate_calls(pc, [-2, -1, -3, -2, 0]), [1010, 1020, 1030, 1040, 1050]\n        )\n\n        # For big jumps, we should perhaps alter the schedule, but we\n        # don't currently. This trace shows that we run callbacks\n        # every 10s of time.time(), but the first and second calls are\n        # 110s of real time apart because the backwards jump is\n        # ignored.\n        self.assertEqual(self.simulate_calls(pc, [-100, 0, 0]), [1010, 1020, 1030])\n\n    def test_jitter(self):\n        random_times = [0.5, 1, 0, 0.75]\n        expected = [1010, 1022.5, 1030, 1041.25]\n        call_durations = [0] * len(random_times)\n        pc = PeriodicCallback(self.dummy, 10000, jitter=0.5)\n\n        def mock_random():\n            return random_times.pop(0)\n\n        with mock.patch(\"random.random\", mock_random):\n            self.assertEqual(self.simulate_calls(pc, call_durations), expected)\n\n    def test_timedelta(self):\n        pc = PeriodicCallback(lambda: None, datetime.timedelta(minutes=1, seconds=23))\n        expected_callback_time = 83000\n        self.assertEqual(pc.callback_time, expected_callback_time)\n\n\nclass TestIOLoopConfiguration(unittest.TestCase):\n    def run_python(self, *statements):\n        stmt_list = [\n            \"from tornado.ioloop import IOLoop\",\n            \"classname = lambda x: x.__class__.__name__\",\n        ] + list(statements)\n        args = [sys.executable, \"-c\", \"; \".join(stmt_list)]\n        return native_str(subprocess.check_output(args)).strip()\n\n    def test_default(self):\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\n    def test_asyncio(self):\n        cls = self.run_python(\n            'IOLoop.configure(\"tornado.platform.asyncio.AsyncIOLoop\")',\n            \"print(classname(IOLoop.current()))\",\n        )\n        self.assertEqual(cls, \"AsyncIOMainLoop\")\n\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        )\n        self.assertEqual(cls, \"AsyncIOMainLoop\")\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": "16848b38",
                "new_commit_hash": "daf74f9b",
                "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": 688,
                            "length": 6
                        },
                        "new_range": {
                            "start": 688,
                            "length": 11
                        },
                        "section": "class TestPeriodicCallbackMath(unittest.TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        with mock.patch(\"random.random\", mock_random):",
                                "type": "context"
                            },
                            {
                                "content": "            self.assertEqual(self.simulate_calls(pc, call_durations), expected)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_timedelta(self):",
                                "type": "added"
                            },
                            {
                                "content": "        pc = PeriodicCallback(lambda: None, datetime.timedelta(minutes=1, seconds=23))",
                                "type": "added"
                            },
                            {
                                "content": "        expected_callback_time = 83000",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(pc.callback_time, expected_callback_time)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "class TestIOLoopConfiguration(unittest.TestCase):",
                                "type": "context"
                            },
                            {
                                "content": "    def run_python(self, *statements):",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "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 (negative values\n        work to simulate clock adjustments during the call, or more or\n        less equivalently, between calls). This method returns the\n        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 dummy(self):\n        pass\n\n    def test_basic(self):\n        pc = PeriodicCallback(self.dummy, 10000)\n        self.assertEqual(\n            self.simulate_calls(pc, [0] * 5), [1010, 1020, 1030, 1040, 1050]\n        )\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,\n            1020,\n            1030,  # first 3 calls on schedule\n            1050,\n            1070,  # next 2 delayed one cycle\n            1100,\n            1130,  # next 2 delayed 2 cycles\n            1170,\n            1210,  # next 2 delayed 3 cycles\n            1220,\n            1230,  # then back on schedule.\n        ]\n\n        pc = PeriodicCallback(self.dummy, 10000)\n        self.assertEqual(self.simulate_calls(pc, call_durations), expected)\n\n    def test_clock_backwards(self):\n        pc = PeriodicCallback(self.dummy, 10000)\n        # Backwards jumps are ignored, potentially resulting in a\n        # slightly slow schedule (although we assume that when\n        # time.time() and time.monotonic() are different, time.time()\n        # is getting adjusted by NTP and is therefore more accurate)\n        self.assertEqual(\n            self.simulate_calls(pc, [-2, -1, -3, -2, 0]), [1010, 1020, 1030, 1040, 1050]\n        )\n\n        # For big jumps, we should perhaps alter the schedule, but we\n        # don't currently. This trace shows that we run callbacks\n        # every 10s of time.time(), but the first and second calls are\n        # 110s of real time apart because the backwards jump is\n        # ignored.\n        self.assertEqual(self.simulate_calls(pc, [-100, 0, 0]), [1010, 1020, 1030])\n\n    def test_jitter(self):\n        random_times = [0.5, 1, 0, 0.75]\n        expected = [1010, 1022.5, 1030, 1041.25]\n        call_durations = [0] * len(random_times)\n        pc = PeriodicCallback(self.dummy, 10000, jitter=0.5)\n\n        def mock_random():\n            return random_times.pop(0)\n\n        with mock.patch(\"random.random\", mock_random):\n            self.assertEqual(self.simulate_calls(pc, call_durations), expected)\n\n    def test_timedelta(self):\n        pc = PeriodicCallback(lambda: None, datetime.timedelta(minutes=1, seconds=23))\n        expected_callback_time = 83000\n        self.assertEqual(pc.callback_time, expected_callback_time)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 614,
                            "end_lineno": 694,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/ioloop_test.py",
                            "type": "method",
                            "name": "TestPeriodicCallbackMath.test_timedelta",
                            "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 (negative values\n        work to simulate clock adjustments during the call, or more or\n        less equivalently, between calls). This method returns the\n        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 dummy(self):\n        pass\n\n    def test_basic(self):\n        pc = PeriodicCallback(self.dummy, 10000)\n        self.assertEqual(\n            self.simulate_calls(pc, [0] * 5), [1010, 1020, 1030, 1040, 1050]\n        )\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,\n            1020,\n            1030,  # first 3 calls on schedule\n            1050,\n            1070,  # next 2 delayed one cycle\n            1100,\n            1130,  # next 2 delayed 2 cycles\n            1170,\n            1210,  # next 2 delayed 3 cycles\n            1220,\n            1230,  # then back on schedule.\n        ]\n\n        pc = PeriodicCallback(self.dummy, 10000)\n        self.assertEqual(self.simulate_calls(pc, call_durations), expected)\n\n    def test_clock_backwards(self):\n        pc = PeriodicCallback(self.dummy, 10000)\n        # Backwards jumps are ignored, potentially resulting in a\n        # slightly slow schedule (although we assume that when\n        # time.time() and time.monotonic() are different, time.time()\n        # is getting adjusted by NTP and is therefore more accurate)\n        self.assertEqual(\n            self.simulate_calls(pc, [-2, -1, -3, -2, 0]), [1010, 1020, 1030, 1040, 1050]\n        )\n\n        # For big jumps, we should perhaps alter the schedule, but we\n        # don't currently. This trace shows that we run callbacks\n        # every 10s of time.time(), but the first and second calls are\n        # 110s of real time apart because the backwards jump is\n        # ignored.\n        self.assertEqual(self.simulate_calls(pc, [-100, 0, 0]), [1010, 1020, 1030])\n\n    def test_jitter(self):\n        random_times = [0.5, 1, 0, 0.75]\n        expected = [1010, 1022.5, 1030, 1041.25]\n        call_durations = [0] * len(random_times)\n        pc = PeriodicCallback(self.dummy, 10000, jitter=0.5)\n\n        def mock_random():\n            return random_times.pop(0)\n\n        with mock.patch(\"random.random\", mock_random):\n            self.assertEqual(self.simulate_calls(pc, call_durations), expected)\n\n    def test_timedelta(self):\n        pc = PeriodicCallback(lambda: None, datetime.timedelta(minutes=1, seconds=23))\n        expected_callback_time = 83000\n        self.assertEqual(pc.callback_time, expected_callback_time)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 691,
                            "end_lineno": 694,
                            "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 (negative values\n        work to simulate clock adjustments during the call, or more or\n        less equivalently, between calls). This method returns the\n        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 dummy(self):\n        pass\n\n    def test_basic(self):\n        pc = PeriodicCallback(self.dummy, 10000)\n        self.assertEqual(\n            self.simulate_calls(pc, [0] * 5), [1010, 1020, 1030, 1040, 1050]\n        )\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,\n            1020,\n            1030,  # first 3 calls on schedule\n            1050,\n            1070,  # next 2 delayed one cycle\n            1100,\n            1130,  # next 2 delayed 2 cycles\n            1170,\n            1210,  # next 2 delayed 3 cycles\n            1220,\n            1230,  # then back on schedule.\n        ]\n\n        pc = PeriodicCallback(self.dummy, 10000)\n        self.assertEqual(self.simulate_calls(pc, call_durations), expected)\n\n    def test_clock_backwards(self):\n        pc = PeriodicCallback(self.dummy, 10000)\n        # Backwards jumps are ignored, potentially resulting in a\n        # slightly slow schedule (although we assume that when\n        # time.time() and time.monotonic() are different, time.time()\n        # is getting adjusted by NTP and is therefore more accurate)\n        self.assertEqual(\n            self.simulate_calls(pc, [-2, -1, -3, -2, 0]), [1010, 1020, 1030, 1040, 1050]\n        )\n\n        # For big jumps, we should perhaps alter the schedule, but we\n        # don't currently. This trace shows that we run callbacks\n        # every 10s of time.time(), but the first and second calls are\n        # 110s of real time apart because the backwards jump is\n        # ignored.\n        self.assertEqual(self.simulate_calls(pc, [-100, 0, 0]), [1010, 1020, 1030])\n\n    def test_jitter(self):\n        random_times = [0.5, 1, 0, 0.75]\n        expected = [1010, 1022.5, 1030, 1041.25]\n        call_durations = [0] * len(random_times)\n        pc = PeriodicCallback(self.dummy, 10000, jitter=0.5)\n\n        def mock_random():\n            return random_times.pop(0)\n\n        with mock.patch(\"random.random\", mock_random):\n            self.assertEqual(self.simulate_calls(pc, call_durations), expected)\n\n    def test_timedelta(self):\n        pc = PeriodicCallback(lambda: None, datetime.timedelta(minutes=1, seconds=23))\n        expected_callback_time = 83000\n        self.assertEqual(pc.callback_time, expected_callback_time)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 614,
                                "end_lineno": 694,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "44ebfc35719774655deb61011f881b7387cde397^",
    "new_commit_hash": "44ebfc35719774655deb61011f881b7387cde397",
    "commit_message": "Optionally accept a timedelta in PeriodicCallback",
    "commit_date": "2021-05-05T09:53:49-06:00",
    "metadata": {}
}
{
    "repo_name": "tornado",
    "new_commit_hash": "44ebfc35719774655deb61011f881b7387cde397",
    "test_file_codes": [
        "from concurrent.futures import ThreadPoolExecutor\nfrom concurrent import futures\nimport contextlib\nimport datetime\nimport functools\nimport socket\nimport subprocess\nimport sys\nimport threading\nimport time\nimport types\nfrom unittest import mock\nimport unittest\n\nfrom tornado.escape import native_str\nfrom tornado import gen\nfrom tornado.ioloop import IOLoop, TimeoutError, PeriodicCallback\nfrom tornado.log import app_log\nfrom tornado.testing import AsyncTestCase, bind_unused_port, ExpectLog, gen_test\nfrom tornado.test.util import skipIfNonUnix, skipOnTravis\n\nimport typing\n\nif typing.TYPE_CHECKING:\n    from typing import List  # noqa: F401\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)  # type: ignore\n        loop.add_callback(lambda: {})  # type: ignore\n        loop.add_callback(lambda: [])  # type: ignore\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\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\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(\n                sock.fileno(), lambda fd, events: None, IOLoop.READ\n            )\n            # Attempting to add the same handler twice fails\n            # (with a platform-dependent exception)\n            self.assertRaises(\n                Exception,\n                self.io_loop.add_handler,\n                sock.fileno(),\n                lambda fd, events: None,\n                IOLoop.READ,\n            )\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\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    @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\n            def handler(fd, events):\n                self.assertEqual(events, IOLoop.READ)\n                self.stop()\n\n            self.io_loop.add_handler(client.fileno(), handler, IOLoop.READ)\n            self.io_loop.add_timeout(\n                self.io_loop.time() + 0.01, functools.partial(server.send, b\"asdf\")  # type: ignore\n            )\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, 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\n        self.io_loop.add_timeout(now + 0.01, t1)\n\n        def t2():\n            calls[1] = True\n\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 = []  # type: List[int]\n        self.io_loop.add_timeout(self.io_loop.time(), results.append, 1)\n        self.io_loop.add_timeout(datetime.timedelta(seconds=0), 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.\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\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, 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\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, 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\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\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        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\n        @gen.coroutine\n        def callback():\n            self.io_loop.add_callback(self.stop)\n            1 / 0\n\n        self.io_loop.add_callback(callback)\n        with ExpectLog(app_log, \"Exception in callback\"):\n            self.wait()\n\n    def test_exception_logging_native_coro(self):\n        \"\"\"The IOLoop examines exceptions from awaitables and logs them.\"\"\"\n\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        self.io_loop.add_callback(callback)\n        with ExpectLog(app_log, \"Exception in callback\"):\n            self.wait()\n\n    def test_spawn_callback(self):\n        # Both add_callback and spawn_callback run directly on the IOLoop,\n        # so their errors are logged without stopping the test.\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        # 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\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    @skipIfNonUnix\n    @gen_test\n    def test_init_close_race(self):\n        # Regression test for #2367\n        #\n        # Skipped on windows because of what looks like a bug in the\n        # proactor event loop when started and stopped on non-main\n        # threads.\n        def f():\n            for i in range(10):\n                loop = IOLoop()\n                loop.close()\n\n        yield gen.multi([self.io_loop.run_in_executor(None, f) for i in range(2)])\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  # type: typing.Optional[IOLoop]\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\n            def f():\n                self.current_io_loop = IOLoop.current()\n                assert self.io_loop is not None\n                self.io_loop.stop()\n\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 TestIOLoopFutures(AsyncTestCase):\n    def test_add_future_threads(self):\n        with futures.ThreadPoolExecutor(1) as pool:\n\n            def dummy():\n                pass\n\n            self.io_loop.add_future(\n                pool.submit(dummy), lambda future: self.stop(future)\n            )\n            future = self.wait()\n            self.assertTrue(future.done())\n            self.assertTrue(future.result() is None)\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    @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 concurrent future would do that).\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 [async_wrapper(event1, event2), async_wrapper(event2, event1)]\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().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\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\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\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\n        self.assertRaises(TimeoutError, self.io_loop.run_sync, f, timeout=0.01)\n\n    def test_native_coroutine(self):\n        @gen.coroutine\n        def f1():\n            yield gen.moment\n\n        async def f2():\n            await f1()\n\n        self.io_loop.run_sync(f2)\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 (negative values\n        work to simulate clock adjustments during the call, or more or\n        less equivalently, between calls). This method returns the\n        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 dummy(self):\n        pass\n\n    def test_basic(self):\n        pc = PeriodicCallback(self.dummy, 10000)\n        self.assertEqual(\n            self.simulate_calls(pc, [0] * 5), [1010, 1020, 1030, 1040, 1050]\n        )\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,\n            1020,\n            1030,  # first 3 calls on schedule\n            1050,\n            1070,  # next 2 delayed one cycle\n            1100,\n            1130,  # next 2 delayed 2 cycles\n            1170,\n            1210,  # next 2 delayed 3 cycles\n            1220,\n            1230,  # then back on schedule.\n        ]\n\n        pc = PeriodicCallback(self.dummy, 10000)\n        self.assertEqual(self.simulate_calls(pc, call_durations), expected)\n\n    def test_clock_backwards(self):\n        pc = PeriodicCallback(self.dummy, 10000)\n        # Backwards jumps are ignored, potentially resulting in a\n        # slightly slow schedule (although we assume that when\n        # time.time() and time.monotonic() are different, time.time()\n        # is getting adjusted by NTP and is therefore more accurate)\n        self.assertEqual(\n            self.simulate_calls(pc, [-2, -1, -3, -2, 0]), [1010, 1020, 1030, 1040, 1050]\n        )\n\n        # For big jumps, we should perhaps alter the schedule, but we\n        # don't currently. This trace shows that we run callbacks\n        # every 10s of time.time(), but the first and second calls are\n        # 110s of real time apart because the backwards jump is\n        # ignored.\n        self.assertEqual(self.simulate_calls(pc, [-100, 0, 0]), [1010, 1020, 1030])\n\n    def test_jitter(self):\n        random_times = [0.5, 1, 0, 0.75]\n        expected = [1010, 1022.5, 1030, 1041.25]\n        call_durations = [0] * len(random_times)\n        pc = PeriodicCallback(self.dummy, 10000, jitter=0.5)\n\n        def mock_random():\n            return random_times.pop(0)\n\n        with mock.patch(\"random.random\", mock_random):\n            self.assertEqual(self.simulate_calls(pc, call_durations), expected)\n\n    def test_timedelta(self):\n        pc = PeriodicCallback(lambda: None, datetime.timedelta(minutes=1, seconds=23))\n        expected_callback_time = 83000\n        self.assertEqual(pc.callback_time, expected_callback_time)\n\n\nclass TestIOLoopConfiguration(unittest.TestCase):\n    def run_python(self, *statements):\n        stmt_list = [\n            \"from tornado.ioloop import IOLoop\",\n            \"classname = lambda x: x.__class__.__name__\",\n        ] + list(statements)\n        args = [sys.executable, \"-c\", \"; \".join(stmt_list)]\n        return native_str(subprocess.check_output(args)).strip()\n\n    def test_default(self):\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\n    def test_asyncio(self):\n        cls = self.run_python(\n            'IOLoop.configure(\"tornado.platform.asyncio.AsyncIOLoop\")',\n            \"print(classname(IOLoop.current()))\",\n        )\n        self.assertEqual(cls, \"AsyncIOMainLoop\")\n\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        )\n        self.assertEqual(cls, \"AsyncIOMainLoop\")\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 861ms\nPrepared 1 package in 1.04s\nInstalled 1 package in 1ms\n + tornado==6.2.dev1 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_44ebfc35719774655deb61011f881b7387cde397)\nResolved 29 packages in 8ms\nInstalled 29 packages in 90ms\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_44ebfc35719774655deb61011f881b7387cde397\n..................................................\ncollected 50 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_handler_callback_file_object\nPASSED r2e_tests.test_1::TestIOLoop::test_init_close_race\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::TestIOLoopConfiguration::test_asyncio\nPASSED r2e_tests.test_1::TestIOLoopConfiguration::test_asyncio_main\nPASSED r2e_tests.test_1::TestIOLoopConfiguration::test_default\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_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\nPASSED r2e_tests.test_1::TestPeriodicCallbackMath::test_basic\nPASSED r2e_tests.test_1::TestPeriodicCallbackMath::test_clock_backwards\nPASSED r2e_tests.test_1::TestPeriodicCallbackMath::test_jitter\nPASSED r2e_tests.test_1::TestPeriodicCallbackMath::test_overrun\nPASSED r2e_tests.test_1::TestPeriodicCallbackMath::test_timedelta\n=================== 50 passed 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_44ebfc35719774655deb61011f881b7387cde397\n..................................................\ncollected 50 items\n\n=================================== ERRORS =====================================\n__________ TestPeriodicCallbackMath.test_timedelta __________\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_44ebfc35719774655deb61011f881b7387cde397/r2e_tests/test_1.py\", line 692, in test_timedelta\n    pc = PeriodicCallback(lambda: None, datetime.timedelta(minutes=1, seconds=23))\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_44ebfc35719774655deb61011f881b7387cde397/tornado/ioloop.py\", line 870, in __init__\n    if callback_time <= 0:\nTypeError: '<=' not supported between instances of 'datetime.timedelta' and 'int'\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_handler_callback_file_object\nPASSED r2e_tests.test_1::TestIOLoop::test_init_close_race\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::TestIOLoopConfiguration::test_asyncio\nPASSED r2e_tests.test_1::TestIOLoopConfiguration::test_asyncio_main\nPASSED r2e_tests.test_1::TestIOLoopConfiguration::test_default\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_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\nPASSED r2e_tests.test_1::TestPeriodicCallbackMath::test_basic\nPASSED r2e_tests.test_1::TestPeriodicCallbackMath::test_clock_backwards\nPASSED r2e_tests.test_1::TestPeriodicCallbackMath::test_jitter\nPASSED r2e_tests.test_1::TestPeriodicCallbackMath::test_overrun\nERROR r2e_tests.test_1::TestPeriodicCallbackMath::test_timedelta\n=================== 1 error, 49 passed in 0.52s ===================\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:** TypeError When Passing `datetime.timedelta` to `PeriodicCallback`

**Description:**
When initializing a `PeriodicCallback` with a `datetime.timedelta` object for the `callback_time`, a `TypeError` is raised. This occurs because the existing implementation expects a float and attempts to compare the `timedelta` with an integer, which is not supported.

**Example Buggy Code:**
```python
from tornado.ioloop import PeriodicCallback
import datetime

# Attempting to use timedelta for callback_time
pc = PeriodicCallback(lambda: None, datetime.timedelta(minutes=1, seconds=23))
```

**Expected Behavior:**
`PeriodicCallback` should accept a `datetime.timedelta` for `callback_time`, convert it appropriately (e.g., to milliseconds), and initialize without errors.

**Actual Behavior:**
A `TypeError` is raised:
```
TypeError: '<=' not supported between instances of 'datetime.timedelta' and 'int'
```
[/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.

In Tornado 6.0, `.IOLoop` is a wrapper around the `asyncio` event
loop, with a slightly different interface for historical reasons.
Applications can use either the `.IOLoop` interface or the underlying
`asyncio` event loop directly (unless compatibility with older
versions of Tornado is desired, in which case `.IOLoop` must be used).

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.

"""

import asyncio
import concurrent.futures
import datetime
import functools
import logging
import numbers
import os
import sys
import time
import math
import random

from tornado.concurrent import (
    Future,
    is_future,
    chain_future,
    future_set_exc_info,
    future_add_done_callback,
)
from tornado.log import app_log
from tornado.util import Configurable, TimeoutError, import_object

import typing
from typing import Union, Any, Type, Optional, Callable, TypeVar, Tuple, Awaitable

if typing.TYPE_CHECKING:
    from typing import Dict, List  # noqa: F401

    from typing_extensions import Protocol
else:
    Protocol = object


class _Selectable(Protocol):
    def fileno(self) -> int:
        pass

    def close(self) -> None:
        pass


_T = TypeVar("_T")
_S = TypeVar("_S", bound=_Selectable)


class IOLoop(Configurable):
    """An I/O event loop.

    As of Tornado 6.0, `IOLoop` is a wrapper around the `asyncio` event
    loop.

    Example usage for a simple TCP server:

    .. testcode::

        import errno
        import functools
        import socket

        import tornado.ioloop
        from tornado.iostream import IOStream

        async def handle_connection(connection, address):
            stream = IOStream(connection)
            message = await 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 BlockingIOError:
                    return
                connection.setblocking(0)
                io_loop = tornado.ioloop.IOLoop.current()
                io_loop.spawn_callback(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.

    """

    # These constants were originally based on constants from the epoll module.
    NONE = 0
    READ = 0x001
    WRITE = 0x004
    ERROR = 0x018

    # In Python 3, _ioloop_for_asyncio maps from asyncio loops to IOLoops.
    _ioloop_for_asyncio = dict()  # type: Dict[asyncio.AbstractEventLoop, IOLoop]

    @classmethod
    def configure(
        cls, impl: "Union[None, str, Type[Configurable]]", **kwargs: Any
    ) -> None:
        if asyncio is not None:
            from tornado.platform.asyncio import BaseAsyncIOLoop

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

    @staticmethod
    def instance() -> "IOLoop":
        """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) -> None:
        """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() -> None:
        """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()

    @typing.overload
    @staticmethod
    def current() -> "IOLoop":
        pass

    @typing.overload
    @staticmethod
    def current(instance: bool = True) -> Optional["IOLoop"]:  # noqa: F811
        pass

    @staticmethod
    def current(instance: bool = True) -> Optional["IOLoop"]:  # noqa: F811
        """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.
        """
        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)  # type: Optional[IOLoop]
            else:
                current = None
        return current

    def make_current(self) -> None:
        """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.
        raise NotImplementedError()

    @staticmethod
    def clear_current() -> None:
        """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) -> None:
        """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) -> Type[Configurable]:
        return IOLoop

    @classmethod
    def configurable_default(cls) -> Type[Configurable]:
        from tornado.platform.asyncio import AsyncIOLoop

        return AsyncIOLoop

    def initialize(self, make_current: Optional[bool] = None) -> 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: bool = False) -> None:
        """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()

    @typing.overload
    def add_handler(
        self, fd: int, handler: Callable[[int, int], None], events: int
    ) -> None:
        pass

    @typing.overload  # noqa: F811
    def add_handler(
        self, fd: _S, handler: Callable[[_S, int], None], events: int
    ) -> None:
        pass

    def add_handler(  # noqa: F811
        self, fd: Union[int, _Selectable], handler: Callable[..., None], events: int
    ) -> None:
        """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()`` and ``close()`` method.

        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: Union[int, _Selectable], events: int) -> None:
        """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: Union[int, _Selectable]) -> None:
        """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 start(self) -> None:
        """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) -> None:
        """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) -> None:
        """Stop the I/O loop.

        If the event loop is not currently running, the next call to `start()`
        will return immediately.

        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: Callable, timeout: Optional[float] = None) -> Any:
        """Starts the `IOLoop`, runs the given function, and stops the loop.

        The function must return either an awaitable object or
        ``None``. If the function returns an awaitable object, the
        `IOLoop` will run until the awaitable is resolved (and
        `run_sync()` will return the awaitable'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 to allow asynchronous calls in a
        ``main()`` function::

            async def main():
                # do stuff...

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

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

        .. versionchanged:: 5.0
           If a timeout occurs, the ``func`` coroutine will be cancelled.

        """
        future_cell = [None]  # type: List[Optional[Future]]

        def run() -> None:
            try:
                result = func()
                if result is not None:
                    from tornado.gen import convert_yielded

                    result = convert_yielded(result)
            except Exception:
                fut = Future()  # type: Future[Any]
                future_cell[0] = fut
                future_set_exc_info(fut, sys.exc_info())
            else:
                if is_future(result):
                    future_cell[0] = result
                else:
                    fut = Future()
                    future_cell[0] = fut
                    fut.set_result(result)
            assert future_cell[0] is not None
            self.add_future(future_cell[0], lambda future: self.stop())

        self.add_callback(run)
        if timeout is not None:

            def timeout_callback() -> None:
                # 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).
                assert future_cell[0] is not None
                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)
        assert future_cell[0] is not None
        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) -> float:
        """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.

        Historically, the IOLoop could be customized to use e.g.
        `time.monotonic` instead of `time.time`, but this is not
        currently supported and so this method is equivalent to
        `time.time`.

        """
        return time.time()

    def add_timeout(
        self,
        deadline: Union[float, datetime.timedelta],
        callback: Callable[..., None],
        *args: Any,
        **kwargs: Any
    ) -> object:
        """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() + deadline.total_seconds(), callback, *args, **kwargs
            )
        else:
            raise TypeError("Unsupported deadline %r" % deadline)

    def call_later(
        self, delay: float, callback: Callable[..., None], *args: Any, **kwargs: Any
    ) -> object:
        """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: float, callback: Callable[..., None], *args: Any, **kwargs: Any
    ) -> object:
        """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: object) -> None:
        """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: Callable, *args: Any, **kwargs: Any) -> None:
        """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: Callable, *args: Any, **kwargs: Any
    ) -> None:
        """Calls the given callback on the next I/O loop iteration.

        Safe for use from a Python signal handler; should not be used
        otherwise.
        """
        raise NotImplementedError()

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

        As of Tornado 6.0, this method is equivalent to `add_callback`.

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

    def add_future(
        self,
        future: "Union[Future[_T], concurrent.futures.Future[_T]]",
        callback: Callable[["Future[_T]"], None],
    ) -> None:
        """Schedules a callback on the ``IOLoop`` when the given
        `.Future` is finished.

        The callback is invoked with one argument, the
        `.Future`.

        This method only accepts `.Future` objects and not other
        awaitables (unlike most of Tornado where the two are
        interchangeable).
        """
        if isinstance(future, Future):
            # Note that we specifically do not want the inline behavior of
            # tornado.concurrent.future_add_done_callback. We always want
            # this callback scheduled on the next IOLoop iteration (which
            # asyncio.Future always does).
            #
            # Wrap the callback in self._run_callback so we control
            # the error logging (i.e. it goes to tornado.log.app_log
            # instead of asyncio's log).
            future.add_done_callback(
                lambda f: self._run_callback(functools.partial(callback, future))
            )
        else:
            assert is_future(future)
            # For concurrent futures, we use self.add_callback, so
            # it's fine if future_add_done_callback inlines that call.
            future_add_done_callback(
                future, lambda f: self.add_callback(callback, future)
            )

    def run_in_executor(
        self,
        executor: Optional[concurrent.futures.Executor],
        func: Callable[..., _T],
        *args: Any
    ) -> Awaitable[_T]:
        """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 executor is None:
            if not hasattr(self, "_executor"):
                from tornado.process import cpu_count

                self._executor = concurrent.futures.ThreadPoolExecutor(
                    max_workers=(cpu_count() * 5)
                )  # type: concurrent.futures.Executor
            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()  # type: Future[_T]
        self.add_future(c_future, lambda f: chain_future(f, t_future))
        return t_future

    def set_default_executor(self, executor: concurrent.futures.Executor) -> None:
        """Sets the default executor to use with :meth:`run_in_executor`.

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

    def _run_callback(self, callback: Callable[[], Any]) -> None:
        """Runs a callback with error handling.

        .. versionchanged:: 6.0

           CancelledErrors are no longer logged.
        """
        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 asyncio.CancelledError:
            pass
        except Exception:
            app_log.error("Exception in callback %r", callback, exc_info=True)

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

    def split_fd(
        self, fd: Union[int, _Selectable]
    ) -> Tuple[int, Union[int, _Selectable]]:
        # """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
        # """
        if isinstance(fd, int):
            return fd, fd
        return fd.fileno(), fd

    def close_fd(self, fd: Union[int, _Selectable]) -> None:
        # """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:
            if isinstance(fd, int):
                os.close(fd)
            else:
                fd.close()
        except OSError:
            pass


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: float, callback: Callable[[], None], io_loop: IOLoop
    ) -> None:
        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),
        )  # type: Tuple[float, int]

    # 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: "_Timeout") -> bool:
        return self.tdeadline < other.tdeadline

    def __le__(self, other: "_Timeout") -> bool:
        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 ``jitter`` is specified, each callback time will be randomly selected
    within a window of ``jitter * callback_time`` milliseconds.
    Jitter can be used to reduce alignment of events with similar periods.
    A jitter of 0.1 means allowing a 10% variation in callback time.
    The window is centered on ``callback_time`` so the total number of calls
    within a given interval should not be significantly affected by adding
    jitter.

    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.

    .. versionchanged:: 5.1
       The ``jitter`` argument is added.
    """

    def __init__(
        self, callback: Callable[[], None], callback_time: float, jitter: float = 0
    ) -> None:
        self.callback = callback
        if callback_time <= 0:
            raise ValueError("Periodic callback must have a positive callback_time")
        self.callback_time = callback_time
        self.jitter = jitter
        self._running = False
        self._timeout = None  # type: object

    def start(self) -> None:
        """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) -> None:
        """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) -> bool:
        """Returns ``True`` if this `.PeriodicCallback` has been started.

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

    def _run(self) -> None:
        if not self._running:
            return
        try:
            return self.callback()
        except Exception:
            app_log.error("Exception in callback %r", self.callback, exc_info=True)
        finally:
            self._schedule_next()

    def _schedule_next(self) -> None:
        if self._running:
            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: float) -> None:
        callback_time_sec = self.callback_time / 1000.0
        if self.jitter:
            # apply jitter fraction
            callback_time_sec *= 1 + (self.jitter * (random.random() - 0.5))
        if self._next_timeout <= current_time:
            # The period should be measured from the start of one call
            # to the start of the next. If one call takes too long,
            # skip cycles to get back to a multiple of the original
            # schedule.
            self._next_timeout += (
                math.floor((current_time - self._next_timeout) / callback_time_sec) + 1
            ) * callback_time_sec
        else:
            # If the clock moved backwards, ensure we advance the next
            # timeout instead of recomputing the same value again.
            # This may result in long gaps between callbacks if the
            # clock jumps backwards by a lot, but the far more common
            # scenario is a small NTP adjustment that should just be
            # ignored.
            #
            # Note that on some systems if time.time() runs slower
            # than time.monotonic() (most common on windows), we
            # effectively experience a small backwards time jump on
            # every iteration because PeriodicCallback uses
            # time.time() while asyncio schedules callbacks using
            # time.monotonic().
            # https://github.com/tornadoweb/tornado/issues/2333
            self._next_timeout += callback_time_sec

```
--- 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:** TypeError When Passing `datetime.timedelta` to `PeriodicCallback`

**Description:**
When initializing a `PeriodicCallback` with a `datetime.timedelta` object for the `callback_time`, a `TypeError` is raised. This occurs because the existing implementation expects a float and attempts to compare the `timedelta` with an integer, which is not supported.

**Example Buggy Code:**
```python
from tornado.ioloop import PeriodicCallback
import datetime

# Attempting to use timedelta for callback_time
pc = PeriodicCallback(lambda: None, datetime.timedelta(minutes=1, seconds=23))
```

**Expected Behavior:**
`PeriodicCallback` should accept a `datetime.timedelta` for `callback_time`, convert it appropriately (e.g., to milliseconds), and initialize without errors.

**Actual Behavior:**
A `TypeError` is raised:
```
TypeError: '<=' not supported between instances of 'datetime.timedelta' and 'int'
```
[/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_handler_callback_file_object": "PASSED",
    "TestIOLoop.test_init_close_race": "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",
    "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_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_clock_backwards": "PASSED",
    "TestPeriodicCallbackMath.test_jitter": "PASSED",
    "TestPeriodicCallbackMath.test_overrun": "PASSED",
    "TestPeriodicCallbackMath.test_timedelta": "PASSED"
}
diff --git a/tornado/ioloop.py b/tornado/ioloop.py
index 2cf88445..fff29cef 100644
--- a/tornado/ioloop.py
+++ b/tornado/ioloop.py
@@ -864,12 +864,18 @@ class PeriodicCallback(object):
     """
 
     def __init__(
-        self, callback: Callable[[], None], callback_time: float, jitter: float = 0
+        self,
+        callback: Callable[[], None],
+        callback_time: Union[datetime.timedelta, float],
+        jitter: float = 0,
     ) -> None:
         self.callback = callback
-        if callback_time <= 0:
-            raise ValueError("Periodic callback must have a positive callback_time")
-        self.callback_time = callback_time
+        if isinstance(callback_time, datetime.timedelta):
+            self.callback_time = callback_time / datetime.timedelta(milliseconds=1)
+        else:
+            if callback_time <= 0:
+                raise ValueError("Periodic callback must have a positive callback_time")
+            self.callback_time = callback_time
         self.jitter = jitter
         self._running = False
         self._timeout = None  # type: object

{"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\nIn Tornado 6.0, `.IOLoop` is a wrapper around the `asyncio` event\nloop, with a slightly different interface for historical reasons.\nApplications can use either the `.IOLoop` interface or the underlying\n`asyncio` event loop directly (unless compatibility with older\nversions of Tornado is desired, in which case `.IOLoop` must be used).\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\n\"\"\"\n\nimport asyncio\nimport concurrent.futures\nimport datetime\nimport functools\nimport logging\nimport numbers\nimport os\nimport sys\nimport time\nimport math\nimport random\n\nfrom tornado.concurrent import (\n    Future,\n    is_future,\n    chain_future,\n    future_set_exc_info,\n    future_add_done_callback,\n)\nfrom tornado.log import app_log\nfrom tornado.util import Configurable, TimeoutError, import_object\n\nimport typing\nfrom typing import Union, Any, Type, Optional, Callable, TypeVar, Tuple, Awaitable\n\nif typing.TYPE_CHECKING:\n    from typing import Dict, List  # noqa: F401\n\n    from typing_extensions import Protocol\nelse:\n    Protocol = object\n\n\nclass _Selectable(Protocol):\n    def fileno(self) -> int:\n        pass\n\n    def close(self) -> None:\n        pass\n\n\n_T = TypeVar(\"_T\")\n_S = TypeVar(\"_S\", bound=_Selectable)\n\n\nclass IOLoop(Configurable):\n    \"\"\"An I/O event loop.\n\n    As of Tornado 6.0, `IOLoop` is a wrapper around the `asyncio` event\n    loop.\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.iostream import IOStream\n\n        async def handle_connection(connection, address):\n            stream = IOStream(connection)\n            message = await 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 BlockingIOError:\n                    return\n                connection.setblocking(0)\n                io_loop = tornado.ioloop.IOLoop.current()\n                io_loop.spawn_callback(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\n    # These constants were originally based on constants from the epoll module.\n    NONE = 0\n    READ = 0x001\n    WRITE = 0x004\n    ERROR = 0x018\n\n    # In Python 3, _ioloop_for_asyncio maps from asyncio loops to IOLoops.\n    _ioloop_for_asyncio = dict()  # type: Dict[asyncio.AbstractEventLoop, IOLoop]\n\n    @classmethod\n    def configure(\n        cls, impl: \"Union[None, str, Type[Configurable]]\", **kwargs: Any\n    ) -> None:\n        if asyncio is not None:\n            from tornado.platform.asyncio import BaseAsyncIOLoop\n\n            if isinstance(impl, str):\n                impl = import_object(impl)\n            if isinstance(impl, type) and not issubclass(impl, BaseAsyncIOLoop):\n                raise RuntimeError(\n                    \"only AsyncIOLoop is allowed when asyncio is available\"\n                )\n        super(IOLoop, cls).configure(impl, **kwargs)\n\n    @staticmethod\n    def instance() -> \"IOLoop\":\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) -> None:\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() -> None:\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    @typing.overload\n    @staticmethod\n    def current() -> \"IOLoop\":\n        pass\n\n    @typing.overload\n    @staticmethod\n    def current(instance: bool = True) -> Optional[\"IOLoop\"]:  # noqa: F811\n        pass\n\n    @staticmethod\n    def current(instance: bool = True) -> Optional[\"IOLoop\"]:  # noqa: F811\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        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\n                current = AsyncIOMainLoop(make_current=True)  # type: Optional[IOLoop]\n            else:\n                current = None\n        return current\n\n    def make_current(self) -> None:\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        raise NotImplementedError()\n\n    @staticmethod\n    def clear_current() -> None:\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) -> None:\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) -> Type[Configurable]:\n        return IOLoop\n\n    @classmethod\n    def configurable_default(cls) -> Type[Configurable]:\n        from tornado.platform.asyncio import AsyncIOLoop\n\n        return AsyncIOLoop\n\n    def initialize(self, make_current: Optional[bool] = None) -> 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: bool = False) -> None:\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    @typing.overload\n    def add_handler(\n        self, fd: int, handler: Callable[[int, int], None], events: int\n    ) -> None:\n        pass\n\n    @typing.overload  # noqa: F811\n    def add_handler(\n        self, fd: _S, handler: Callable[[_S, int], None], events: int\n    ) -> None:\n        pass\n\n    def add_handler(  # noqa: F811\n        self, fd: Union[int, _Selectable], handler: Callable[..., None], events: int\n    ) -> None:\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()`` and ``close()`` method.\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: Union[int, _Selectable], events: int) -> None:\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: Union[int, _Selectable]) -> None:\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 start(self) -> None:\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) -> None:\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(\n            [\n                logging.getLogger().handlers,\n                logging.getLogger(\"tornado\").handlers,\n                logging.getLogger(\"tornado.application\").handlers,\n            ]\n        ):\n            logging.basicConfig()\n\n    def stop(self) -> None:\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        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: Callable, timeout: Optional[float] = None) -> Any:\n        \"\"\"Starts the `IOLoop`, runs the given function, and stops the loop.\n\n        The function must return either an awaitable object or\n        ``None``. If the function returns an awaitable object, the\n        `IOLoop` will run until the awaitable is resolved (and\n        `run_sync()` will return the awaitable'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 to allow asynchronous calls in a\n        ``main()`` function::\n\n            async 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-awaitable value is now an error.\n\n        .. versionchanged:: 5.0\n           If a timeout occurs, the ``func`` coroutine will be cancelled.\n\n        \"\"\"\n        future_cell = [None]  # type: List[Optional[Future]]\n\n        def run() -> None:\n            try:\n                result = func()\n                if result is not None:\n                    from tornado.gen import convert_yielded\n\n                    result = convert_yielded(result)\n            except Exception:\n                fut = Future()  # type: Future[Any]\n                future_cell[0] = fut\n                future_set_exc_info(fut, sys.exc_info())\n            else:\n                if is_future(result):\n                    future_cell[0] = result\n                else:\n                    fut = Future()\n                    future_cell[0] = fut\n                    fut.set_result(result)\n            assert future_cell[0] is not None\n            self.add_future(future_cell[0], lambda future: self.stop())\n\n        self.add_callback(run)\n        if timeout is not None:\n\n            def timeout_callback() -> None:\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                assert future_cell[0] is not None\n                if not future_cell[0].cancel():\n                    self.stop()\n\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        assert future_cell[0] is not None\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) -> float:\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        Historically, the IOLoop could be customized to use e.g.\n        `time.monotonic` instead of `time.time`, but this is not\n        currently supported and so this method is equivalent to\n        `time.time`.\n\n        \"\"\"\n        return time.time()\n\n    def add_timeout(\n        self,\n        deadline: Union[float, datetime.timedelta],\n        callback: Callable[..., None],\n        *args: Any,\n        **kwargs: Any\n    ) -> object:\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(\n                self.time() + deadline.total_seconds(), callback, *args, **kwargs\n            )\n        else:\n            raise TypeError(\"Unsupported deadline %r\" % deadline)\n\n    def call_later(\n        self, delay: float, callback: Callable[..., None], *args: Any, **kwargs: Any\n    ) -> object:\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(\n        self, when: float, callback: Callable[..., None], *args: Any, **kwargs: Any\n    ) -> object:\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: object) -> None:\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: Callable, *args: Any, **kwargs: Any) -> None:\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(\n        self, callback: Callable, *args: Any, **kwargs: Any\n    ) -> None:\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        raise NotImplementedError()\n\n    def spawn_callback(self, callback: Callable, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Calls the given callback on the next IOLoop iteration.\n\n        As of Tornado 6.0, this method is equivalent to `add_callback`.\n\n        .. versionadded:: 4.0\n        \"\"\"\n        self.add_callback(callback, *args, **kwargs)\n\n    def add_future(\n        self,\n        future: \"Union[Future[_T], concurrent.futures.Future[_T]]\",\n        callback: Callable[[\"Future[_T]\"], None],\n    ) -> None:\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        This method only accepts `.Future` objects and not other\n        awaitables (unlike most of Tornado where the two are\n        interchangeable).\n        \"\"\"\n        if isinstance(future, Future):\n            # Note that we specifically do not want the inline behavior of\n            # tornado.concurrent.future_add_done_callback. We always want\n            # this callback scheduled on the next IOLoop iteration (which\n            # asyncio.Future always does).\n            #\n            # Wrap the callback in self._run_callback so we control\n            # the error logging (i.e. it goes to tornado.log.app_log\n            # instead of asyncio's log).\n            future.add_done_callback(\n                lambda f: self._run_callback(functools.partial(callback, future))\n            )\n        else:\n            assert is_future(future)\n            # For concurrent futures, we use self.add_callback, so\n            # it's fine if future_add_done_callback inlines that call.\n            future_add_done_callback(\n                future, lambda f: self.add_callback(callback, future)\n            )\n\n    def run_in_executor(\n        self,\n        executor: Optional[concurrent.futures.Executor],\n        func: Callable[..., _T],\n        *args: Any\n    ) -> Awaitable[_T]:\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 executor is None:\n            if not hasattr(self, \"_executor\"):\n                from tornado.process import cpu_count\n\n                self._executor = concurrent.futures.ThreadPoolExecutor(\n                    max_workers=(cpu_count() * 5)\n                )  # type: concurrent.futures.Executor\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()  # type: Future[_T]\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: concurrent.futures.Executor) -> None:\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: Callable[[], Any]) -> None:\n        \"\"\"Runs a callback with error handling.\n\n        .. versionchanged:: 6.0\n\n           CancelledErrors are no longer logged.\n        \"\"\"\n        try:\n            ret = callback()\n            if ret is not None:\n                from tornado import gen\n\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 asyncio.CancelledError:\n            pass\n        except Exception:\n            app_log.error(\"Exception in callback %r\", callback, exc_info=True)\n\n    def _discard_future_result(self, future: Future) -> None:\n        \"\"\"Avoid unhandled-exception warnings from spawned coroutines.\"\"\"\n        future.result()\n\n    def split_fd(\n        self, fd: Union[int, _Selectable]\n    ) -> Tuple[int, Union[int, _Selectable]]:\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        if isinstance(fd, int):\n            return fd, fd\n        return fd.fileno(), fd\n\n    def close_fd(self, fd: Union[int, _Selectable]) -> None:\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            if isinstance(fd, int):\n                os.close(fd)\n            else:\n                fd.close()\n        except OSError:\n            pass\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__(\n        self, deadline: float, callback: Callable[[], None], io_loop: IOLoop\n    ) -> None:\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 = (\n            deadline,\n            next(io_loop._timeout_counter),\n        )  # type: Tuple[float, int]\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: \"_Timeout\") -> bool:\n        return self.tdeadline < other.tdeadline\n\n    def __le__(self, other: \"_Timeout\") -> bool:\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 ``jitter`` is specified, each callback time will be randomly selected\n    within a window of ``jitter * callback_time`` milliseconds.\n    Jitter can be used to reduce alignment of events with similar periods.\n    A jitter of 0.1 means allowing a 10% variation in callback time.\n    The window is centered on ``callback_time`` so the total number of calls\n    within a given interval should not be significantly affected by adding\n    jitter.\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    .. versionchanged:: 5.1\n       The ``jitter`` argument is added.\n    \"\"\"\n\n    def __init__(\n        self, callback: Callable[[], None], callback_time: float, jitter: float = 0\n    ) -> None:\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.jitter = jitter\n        self._running = False\n        self._timeout = None  # type: object\n\n    def start(self) -> None:\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) -> None:\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) -> bool:\n        \"\"\"Returns ``True`` if this `.PeriodicCallback` has been started.\n\n        .. versionadded:: 4.1\n        \"\"\"\n        return self._running\n\n    def _run(self) -> None:\n        if not self._running:\n            return\n        try:\n            return self.callback()\n        except Exception:\n            app_log.error(\"Exception in callback %r\", self.callback, exc_info=True)\n        finally:\n            self._schedule_next()\n\n    def _schedule_next(self) -> None:\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: float) -> None:\n        callback_time_sec = self.callback_time / 1000.0\n        if self.jitter:\n            # apply jitter fraction\n            callback_time_sec *= 1 + (self.jitter * (random.random() - 0.5))\n        if self._next_timeout <= current_time:\n            # The period should be measured from the start of one call\n            # to the start of the next. If one call takes too long,\n            # skip cycles to get back to a multiple of the original\n            # schedule.\n            self._next_timeout += (\n                math.floor((current_time - self._next_timeout) / callback_time_sec) + 1\n            ) * callback_time_sec\n        else:\n            # If the clock moved backwards, ensure we advance the next\n            # timeout instead of recomputing the same value again.\n            # This may result in long gaps between callbacks if the\n            # clock jumps backwards by a lot, but the far more common\n            # scenario is a small NTP adjustment that should just be\n            # ignored.\n            #\n            # Note that on some systems if time.time() runs slower\n            # than time.monotonic() (most common on windows), we\n            # effectively experience a small backwards time jump on\n            # every iteration because PeriodicCallback uses\n            # time.time() while asyncio schedules callbacks using\n            # time.monotonic().\n            # https://github.com/tornadoweb/tornado/issues/2333\n            self._next_timeout += callback_time_sec\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:** TypeError When Passing `datetime.timedelta` to `PeriodicCallback`

**Description:**
When initializing a `PeriodicCallback` with a `datetime.timedelta` object for the `callback_time`, a `TypeError` is raised. This occurs because the existing implementation expects a float and attempts to compare the `timedelta` with an integer, which is not supported.

**Example Buggy Code:**
```python
from tornado.ioloop import PeriodicCallback
import datetime

# Attempting to use timedelta for callback_time
pc = PeriodicCallback(lambda: None, datetime.timedelta(minutes=1, seconds=23))
```

**Expected Behavior:**
`PeriodicCallback` should accept a `datetime.timedelta` for `callback_time`, convert it appropriately (e.g., to milliseconds), and initialize without errors.

**Actual Behavior:**
A `TypeError` is raised:
```
TypeError: '<=' not supported between instances of 'datetime.timedelta' and 'int'
```
[/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.

In Tornado 6.0, `.IOLoop` is a wrapper around the `asyncio` event
loop, with a slightly different interface for historical reasons.
Applications can use either the `.IOLoop` interface or the underlying
`asyncio` event loop directly (unless compatibility with older
versions of Tornado is desired, in which case `.IOLoop` must be used).

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.

"""

import asyncio
import concurrent.futures
import datetime
import functools
import logging
import numbers
import os
import sys
import time
import math
import random

from tornado.concurrent import (
    Future,
    is_future,
    chain_future,
    future_set_exc_info,
    future_add_done_callback,
)
from tornado.log import app_log
from tornado.util import Configurable, TimeoutError, import_object

import typing
from typing import Union, Any, Type, Optional, Callable, TypeVar, Tuple, Awaitable

if typing.TYPE_CHECKING:
    from typing import Dict, List  # noqa: F401

    from typing_extensions import Protocol
else:
    Protocol = object


class _Selectable(Protocol):
    def fileno(self) -> int:
        pass

    def close(self) -> None:
        pass


_T = TypeVar("_T")
_S = TypeVar("_S", bound=_Selectable)


class IOLoop(Configurable):
    """An I/O event loop.

    As of Tornado 6.0, `IOLoop` is a wrapper around the `asyncio` event
    loop.

    Example usage for a simple TCP server:

    .. testcode::

        import errno
        import functools
        import socket

        import tornado.ioloop
        from tornado.iostream import IOStream

        async def handle_connection(connection, address):
            stream = IOStream(connection)
            message = await 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 BlockingIOError:
                    return
                connection.setblocking(0)
                io_loop = tornado.ioloop.IOLoop.current()
                io_loop.spawn_callback(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.

    """

    # These constants were originally based on constants from the epoll module.
    NONE = 0
    READ = 0x001
    WRITE = 0x004
    ERROR = 0x018

    # In Python 3, _ioloop_for_asyncio maps from asyncio loops to IOLoops.
    _ioloop_for_asyncio = dict()  # type: Dict[asyncio.AbstractEventLoop, IOLoop]

    @classmethod
    def configure(
        cls, impl: "Union[None, str, Type[Configurable]]", **kwargs: Any
    ) -> None:
        if asyncio is not None:
            from tornado.platform.asyncio import BaseAsyncIOLoop

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

    @staticmethod
    def instance() -> "IOLoop":
        """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) -> None:
        """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() -> None:
        """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()

    @typing.overload
    @staticmethod
    def current() -> "IOLoop":
        pass

    @typing.overload
    @staticmethod
    def current(instance: bool = True) -> Optional["IOLoop"]:  # noqa: F811
        pass

    @staticmethod
    def current(instance: bool = True) -> Optional["IOLoop"]:  # noqa: F811
        """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.
        """
        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)  # type: Optional[IOLoop]
            else:
                current = None
        return current

    def make_current(self) -> None:
        """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.
        raise NotImplementedError()

    @staticmethod
    def clear_current() -> None:
        """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) -> None:
        """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) -> Type[Configurable]:
        return IOLoop

    @classmethod
    def configurable_default(cls) -> Type[Configurable]:
        from tornado.platform.asyncio import AsyncIOLoop

        return AsyncIOLoop

    def initialize(self, make_current: Optional[bool] = None) -> 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: bool = False) -> None:
        """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()

    @typing.overload
    def add_handler(
        self, fd: int, handler: Callable[[int, int], None], events: int
    ) -> None:
        pass

    @typing.overload  # noqa: F811
    def add_handler(
        self, fd: _S, handler: Callable[[_S, int], None], events: int
    ) -> None:
        pass

    def add_handler(  # noqa: F811
        self, fd: Union[int, _Selectable], handler: Callable[..., None], events: int
    ) -> None:
        """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()`` and ``close()`` method.

        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: Union[int, _Selectable], events: int) -> None:
        """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: Union[int, _Selectable]) -> None:
        """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 start(self) -> None:
        """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) -> None:
        """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) -> None:
        """Stop the I/O loop.

        If the event loop is not currently running, the next call to `start()`
        will return immediately.

        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: Callable, timeout: Optional[float] = None) -> Any:
        """Starts the `IOLoop`, runs the given function, and stops the loop.

        The function must return either an awaitable object or
        ``None``. If the function returns an awaitable object, the
        `IOLoop` will run until the awaitable is resolved (and
        `run_sync()` will return the awaitable'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 to allow asynchronous calls in a
        ``main()`` function::

            async def main():
                # do stuff...

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

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

        .. versionchanged:: 5.0
           If a timeout occurs, the ``func`` coroutine will be cancelled.

        """
        future_cell = [None]  # type: List[Optional[Future]]

        def run() -> None:
            try:
                result = func()
                if result is not None:
                    from tornado.gen import convert_yielded

                    result = convert_yielded(result)
            except Exception:
                fut = Future()  # type: Future[Any]
                future_cell[0] = fut
                future_set_exc_info(fut, sys.exc_info())
            else:
                if is_future(result):
                    future_cell[0] = result
                else:
                    fut = Future()
                    future_cell[0] = fut
                    fut.set_result(result)
            assert future_cell[0] is not None
            self.add_future(future_cell[0], lambda future: self.stop())

        self.add_callback(run)
        if timeout is not None:

            def timeout_callback() -> None:
                # 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).
                assert future_cell[0] is not None
                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)
        assert future_cell[0] is not None
        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) -> float:
        """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.

        Historically, the IOLoop could be customized to use e.g.
        `time.monotonic` instead of `time.time`, but this is not
        currently supported and so this method is equivalent to
        `time.time`.

        """
        return time.time()

    def add_timeout(
        self,
        deadline: Union[float, datetime.timedelta],
        callback: Callable[..., None],
        *args: Any,
        **kwargs: Any
    ) -> object:
        """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() + deadline.total_seconds(), callback, *args, **kwargs
            )
        else:
            raise TypeError("Unsupported deadline %r" % deadline)

    def call_later(
        self, delay: float, callback: Callable[..., None], *args: Any, **kwargs: Any
    ) -> object:
        """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: float, callback: Callable[..., None], *args: Any, **kwargs: Any
    ) -> object:
        """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: object) -> None:
        """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: Callable, *args: Any, **kwargs: Any) -> None:
        """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: Callable, *args: Any, **kwargs: Any
    ) -> None:
        """Calls the given callback on the next I/O loop iteration.

        Safe for use from a Python signal handler; should not be used
        otherwise.
        """
        raise NotImplementedError()

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

        As of Tornado 6.0, this method is equivalent to `add_callback`.

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

    def add_future(
        self,
        future: "Union[Future[_T], concurrent.futures.Future[_T]]",
        callback: Callable[["Future[_T]"], None],
    ) -> None:
        """Schedules a callback on the ``IOLoop`` when the given
        `.Future` is finished.

        The callback is invoked with one argument, the
        `.Future`.

        This method only accepts `.Future` objects and not other
        awaitables (unlike most of Tornado where the two are
        interchangeable).
        """
        if isinstance(future, Future):
            # Note that we specifically do not want the inline behavior of
            # tornado.concurrent.future_add_done_callback. We always want
            # this callback scheduled on the next IOLoop iteration (which
            # asyncio.Future always does).
            #
            # Wrap the callback in self._run_callback so we control
            # the error logging (i.e. it goes to tornado.log.app_log
            # instead of asyncio's log).
            future.add_done_callback(
                lambda f: self._run_callback(functools.partial(callback, future))
            )
        else:
            assert is_future(future)
            # For concurrent futures, we use self.add_callback, so
            # it's fine if future_add_done_callback inlines that call.
            future_add_done_callback(
                future, lambda f: self.add_callback(callback, future)
            )

    def run_in_executor(
        self,
        executor: Optional[concurrent.futures.Executor],
        func: Callable[..., _T],
        *args: Any
    ) -> Awaitable[_T]:
        """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 executor is None:
            if not hasattr(self, "_executor"):
                from tornado.process import cpu_count

                self._executor = concurrent.futures.ThreadPoolExecutor(
                    max_workers=(cpu_count() * 5)
                )  # type: concurrent.futures.Executor
            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()  # type: Future[_T]
        self.add_future(c_future, lambda f: chain_future(f, t_future))
        return t_future

    def set_default_executor(self, executor: concurrent.futures.Executor) -> None:
        """Sets the default executor to use with :meth:`run_in_executor`.

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

    def _run_callback(self, callback: Callable[[], Any]) -> None:
        """Runs a callback with error handling.

        .. versionchanged:: 6.0

           CancelledErrors are no longer logged.
        """
        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 asyncio.CancelledError:
            pass
        except Exception:
            app_log.error("Exception in callback %r", callback, exc_info=True)

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

    def split_fd(
        self, fd: Union[int, _Selectable]
    ) -> Tuple[int, Union[int, _Selectable]]:
        # """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
        # """
        if isinstance(fd, int):
            return fd, fd
        return fd.fileno(), fd

    def close_fd(self, fd: Union[int, _Selectable]) -> None:
        # """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:
            if isinstance(fd, int):
                os.close(fd)
            else:
                fd.close()
        except OSError:
            pass


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: float, callback: Callable[[], None], io_loop: IOLoop
    ) -> None:
        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),
        )  # type: Tuple[float, int]

    # 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: "_Timeout") -> bool:
        return self.tdeadline < other.tdeadline

    def __le__(self, other: "_Timeout") -> bool:
        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 ``jitter`` is specified, each callback time will be randomly selected
    within a window of ``jitter * callback_time`` milliseconds.
    Jitter can be used to reduce alignment of events with similar periods.
    A jitter of 0.1 means allowing a 10% variation in callback time.
    The window is centered on ``callback_time`` so the total number of calls
    within a given interval should not be significantly affected by adding
    jitter.

    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.

    .. versionchanged:: 5.1
       The ``jitter`` argument is added.
    """

    def __init__(
        self, callback: Callable[[], None], callback_time: float, jitter: float = 0
    ) -> None:
        self.callback = callback
        if callback_time <= 0:
            raise ValueError("Periodic callback must have a positive callback_time")
        self.callback_time = callback_time
        self.jitter = jitter
        self._running = False
        self._timeout = None  # type: object

    def start(self) -> None:
        """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) -> None:
        """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) -> bool:
        """Returns ``True`` if this `.PeriodicCallback` has been started.

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

    def _run(self) -> None:
        if not self._running:
            return
        try:
            return self.callback()
        except Exception:
            app_log.error("Exception in callback %r", self.callback, exc_info=True)
        finally:
            self._schedule_next()

    def _schedule_next(self) -> None:
        if self._running:
            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: float) -> None:
        callback_time_sec = self.callback_time / 1000.0
        if self.jitter:
            # apply jitter fraction
            callback_time_sec *= 1 + (self.jitter * (random.random() - 0.5))
        if self._next_timeout <= current_time:
            # The period should be measured from the start of one call
            # to the start of the next. If one call takes too long,
            # skip cycles to get back to a multiple of the original
            # schedule.
            self._next_timeout += (
                math.floor((current_time - self._next_timeout) / callback_time_sec) + 1
            ) * callback_time_sec
        else:
            # If the clock moved backwards, ensure we advance the next
            # timeout instead of recomputing the same value again.
            # This may result in long gaps between callbacks if the
            # clock jumps backwards by a lot, but the far more common
            # scenario is a small NTP adjustment that should just be
            # ignored.
            #
            # Note that on some systems if time.time() runs slower
            # than time.monotonic() (most common on windows), we
            # effectively experience a small backwards time jump on
            # every iteration because PeriodicCallback uses
            # time.time() while asyncio schedules callbacks using
            # time.monotonic().
            # https://github.com/tornadoweb/tornado/issues/2333
            self._next_timeout += callback_time_sec

```
--- 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