]> git.ipfire.org Git - thirdparty/tornado.git/commitdiff
Introduce gen.sleep().
authorBen Darnell <ben@bendarnell.com>
Mon, 19 Jan 2015 20:38:59 +0000 (15:38 -0500)
committerBen Darnell <ben@bendarnell.com>
Mon, 19 Jan 2015 20:38:59 +0000 (15:38 -0500)
Closes #1146.

tornado/gen.py
tornado/test/gen_test.py

index c9c6f5c1dce755bd7986e92b6baaff37e66117af..11d5aedd2a1898207734d6ab10df52aed73a5097 100644 (file)
@@ -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)
 
index 13ee1a2c5936c1457057f3f01e037025adec0a1d..efc48644a72b796acf35a10d7a672aa42731998c 100644 (file)
@@ -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