Skip to content

Commit

Permalink
Introduce gen.sleep().
Browse files Browse the repository at this point in the history
Closes #1146.
  • Loading branch information
bdarnell committed Jan 19, 2015
1 parent 841b2d4 commit 022c46c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
19 changes: 19 additions & 0 deletions tornado/gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -690,6 +690,25 @@ def timeout_callback():
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)

Expand Down
5 changes: 5 additions & 0 deletions tornado/test/gen_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -838,6 +838,11 @@ def f(name, yieldable):
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
Expand Down

0 comments on commit 022c46c

Please sign in to comment.