]> git.ipfire.org Git - thirdparty/tornado.git/commitdiff
Fetch IOLoop in PeriodicCallback.start(), not __init__() 2179/head
authorAntoine Pitrou <antoine@python.org>
Tue, 24 Oct 2017 09:09:44 +0000 (11:09 +0200)
committerAntoine Pitrou <antoine@python.org>
Tue, 24 Oct 2017 09:09:44 +0000 (11:09 +0200)
See motivation at https://github.com/dask/distributed/pull/1172

tornado/ioloop.py
tornado/test/ioloop_test.py

index 5686576cf7dbe310c3e4d00c67f04ef3d5a0ec5d..631f15a2042a89636dc65bfb2b9a6df87655af6b 100644 (file)
@@ -1082,12 +1082,15 @@ class PeriodicCallback(object):
         if callback_time <= 0:
             raise ValueError("Periodic callback must have a positive callback_time")
         self.callback_time = callback_time
-        self.io_loop = IOLoop.current()
         self._running = False
         self._timeout = None
 
     def start(self):
         """Starts the timer."""
+        # Looking up the IOLoop here allows to first instantiate the
+        # PeriodicCallback in another thread, then start it using
+        # IOLoop.add_callback().
+        self.io_loop = IOLoop.current()
         self._running = True
         self._next_timeout = self.io_loop.time()
         self._schedule_next()
index f3cd32ae42a5b4d1bc52c5cb760addb844bea0a8..bde351f60c834d9bd09f61ff1443353593c99383 100644 (file)
@@ -747,6 +747,21 @@ class TestPeriodicCallback(unittest.TestCase):
         self.io_loop.start()
         self.assertEqual(calls, expected)
 
+    def test_io_loop_set_at_start(self):
+        # Check PeriodicCallback uses the current IOLoop at start() time,
+        # not at instantiation time.
+        calls = []
+        io_loop = FakeTimeIOLoop()
+
+        def cb():
+            calls.append(io_loop.time())
+        pc = PeriodicCallback(cb, 10000)
+        io_loop.make_current()
+        pc.start()
+        io_loop.call_later(50, io_loop.stop)
+        io_loop.start()
+        self.assertEqual(calls, [1010, 1020, 1030, 1040, 1050])
+
 
 class TestIOLoopConfiguration(unittest.TestCase):
     def run_python(self, *statements):