From 022c46c8c2f22e2ac7f04cd7eda1ac943cdc35d7 Mon Sep 17 00:00:00 2001 From: Ben Darnell Date: Mon, 19 Jan 2015 15:38:59 -0500 Subject: [PATCH] Introduce gen.sleep(). Closes #1146. --- tornado/gen.py | 19 +++++++++++++++++++ tornado/test/gen_test.py | 5 +++++ 2 files changed, 24 insertions(+) diff --git a/tornado/gen.py b/tornado/gen.py index c9c6f5c1d..11d5aedd2 100644 --- a/tornado/gen.py +++ b/tornado/gen.py @@ -690,6 +690,25 @@ def with_timeout(timeout, future, io_loop=None, quiet_exceptions=()): return result +def sleep(duration): + """Return a `.Future` that resolves after the given number of seconds. + + When used with ``yield`` in a coroutine, this is a non-blocking + analogue to `time.sleep` (which should not be used in coroutines + because it is blocking):: + + yield gen.sleep(0.5) + + Note that calling this function on its own does nothing; you must + wait on the `.Future` it returns (usually by yielding it). + + .. versionadded:: 4.1 + """ + f = Future() + IOLoop.current().call_later(duration, lambda: f.set_result(None)) + return f + + _null_future = Future() _null_future.set_result(None) diff --git a/tornado/test/gen_test.py b/tornado/test/gen_test.py index 13ee1a2c5..efc48644a 100644 --- a/tornado/test/gen_test.py +++ b/tornado/test/gen_test.py @@ -838,6 +838,11 @@ class GenCoroutineTest(AsyncTestCase): yield [f('a', gen.moment), f('b', immediate)] self.assertEqual(''.join(calls), 'abbbbbaaaa') + @gen_test + def test_sleep(self): + yield gen.sleep(0.01) + self.finished = True + class GenSequenceHandler(RequestHandler): @asynchronous -- 2.47.2