diff options
author | Victor Stinner <victor.stinner@gmail.com> | 2014-10-15 16:49:16 (GMT) |
---|---|---|
committer | Victor Stinner <victor.stinner@gmail.com> | 2014-10-15 16:49:16 (GMT) |
commit | 7f314ed71b29c83bbfce6f11d9a7b3e42b78bf38 (patch) | |
tree | fcf148cf8b9ed616ba3acecdad79b077a0d0a5a6 /Doc/library/asyncio-task.rst | |
parent | 9c422f3c3d0401aff0b2a5151181afcb508c928c (diff) | |
download | cpython-7f314ed71b29c83bbfce6f11d9a7b3e42b78bf38.zip cpython-7f314ed71b29c83bbfce6f11d9a7b3e42b78bf38.tar.gz cpython-7f314ed71b29c83bbfce6f11d9a7b3e42b78bf38.tar.bz2 |
asyncio doc: write simpler examples to introduce asyncio
Diffstat (limited to 'Doc/library/asyncio-task.rst')
-rw-r--r-- | Doc/library/asyncio-task.rst | 56 |
1 files changed, 43 insertions, 13 deletions
diff --git a/Doc/library/asyncio-task.rst b/Doc/library/asyncio-task.rst index fa95ca9..21c4e33 100644 --- a/Doc/library/asyncio-task.rst +++ b/Doc/library/asyncio-task.rst @@ -77,30 +77,60 @@ Coroutines (and tasks) can only run when the event loop is running. .. _asyncio-hello-world-coroutine: -Example: "Hello World" coroutine -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Example: Hello World coroutine +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -Print ``"Hello World"`` every two seconds using a coroutine:: +Example of coroutine displaying ``"Hello World"``:: import asyncio @asyncio.coroutine - def greet_every_two_seconds(): + def hello_world(): + print("Hello World!") + + loop = asyncio.get_event_loop() + # Blocking call which returns when the hello_world() coroutine is done + loop.run_until_complete(hello_world()) + loop.close() + +.. seealso:: + + The :ref:`Hello World with call_soon() <asyncio-hello-world-callback>` + example uses the :meth:`BaseEventLoop.call_soon` method to schedule a + callback. + + +.. _asyncio-date-coroutine: + +Example: Coroutine displaying the current date +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Example of coroutine displaying the current date every second during 5 seconds +using the :meth:`sleep` function:: + + import asyncio + import datetime + + @asyncio.coroutine + def display_date(loop): + end_time = loop.time() + 5.0 while True: - print('Hello World') - yield from asyncio.sleep(2) + print(datetime.datetime.now()) + if (loop.time() + 1.0) >= end_time: + break + yield from asyncio.sleep(1) loop = asyncio.get_event_loop() - try: - loop.run_until_complete(greet_every_two_seconds()) - finally: - loop.close() + # Blocking call which returns when the display_date() coroutine is done + loop.run_until_complete(display_date(loop)) + loop.close() .. seealso:: - The :ref:`Hello World with a callback <asyncio-hello-world-callback>` - example uses a callback scheduled by the :meth:`BaseEventLoop.call_soon` - method. + The :ref:`display the current date with call_later() + <asyncio-date-callback>` example uses a callback with the + :meth:`BaseEventLoop.call_later` method. + Example: Chain coroutines ^^^^^^^^^^^^^^^^^^^^^^^^^ |