Skip to content

Commit

Permalink
Merge pull request tornadoweb#2179 from pitrou/periodic_callback_iolo…
Browse files Browse the repository at this point in the history
…op_compat

Fetch IOLoop in PeriodicCallback.start(), not __init__()
  • Loading branch information
bdarnell authored Oct 28, 2017
2 parents 5ee7f45 + b1a7390 commit 5bc4924
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
5 changes: 4 additions & 1 deletion tornado/ioloop.py
Original file line number Diff line number Diff line change
Expand Up @@ -1086,12 +1086,15 @@ def __init__(self, callback, callback_time):
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()
Expand Down
15 changes: 15 additions & 0 deletions tornado/test/ioloop_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -761,6 +761,21 @@ def cb():
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):
Expand Down

0 comments on commit 5bc4924

Please sign in to comment.