@@ -649,31 +649,70 @@ Event loop examples
649649
650650.. _asyncio-hello-world-callback :
651651
652- Hello World with a callback
653- ---------------------------
652+ Hello World with call_soon()
653+ ----------------------------
654654
655- Print ``"Hello World" `` every two seconds using a callback scheduled by the
656- :meth: `BaseEventLoop.call_soon ` method::
655+ Example using the :meth: `BaseEventLoop.call_soon ` method to schedule a
656+ callback. The callback displays ``"Hello World" `` and then stops the event
657+ loop::
657658
658659 import asyncio
659660
660- def print_and_repeat (loop):
661+ def hello_world (loop):
661662 print('Hello World')
662- loop.call_later(2, print_and_repeat, loop )
663+ loop.stop( )
663664
664665 loop = asyncio.get_event_loop()
665- loop.call_soon(print_and_repeat, loop)
666- try:
667- loop.run_forever()
668- finally:
669- loop.close()
666+
667+ # Schedule a call to hello_world()
668+ loop.call_soon(hello_world, loop)
669+
670+ # Blocking call interrupted by loop.stop()
671+ loop.run_forever()
672+ loop.close()
670673
671674.. seealso ::
672675
673676 The :ref: `Hello World coroutine <asyncio-hello-world-coroutine >` example
674677 uses a :ref: `coroutine <coroutine >`.
675678
676679
680+ .. _asyncio-date-callback :
681+
682+ Display the current date with call_later()
683+ ------------------------------------------
684+
685+ Example of callback displaying the current date every second. The callback uses
686+ the :meth: `BaseEventLoop.call_later ` method to reschedule itself during 5
687+ seconds, and then stops the event loop::
688+
689+ import asyncio
690+ import datetime
691+
692+ def display_date(end_time, loop):
693+ print(datetime.datetime.now())
694+ if (loop.time() + 1.0) < end_time:
695+ loop.call_later(1, display_date, end_time, loop)
696+ else:
697+ loop.stop()
698+
699+ loop = asyncio.get_event_loop()
700+
701+ # Schedule the first call to display_date()
702+ end_time = loop.time() + 5.0
703+ loop.call_soon(display_date, end_time, loop)
704+
705+ # Blocking call interrupted by loop.stop()
706+ loop.run_forever()
707+ loop.close()
708+
709+ .. seealso ::
710+
711+ The :ref: `coroutine displaying the current date
712+ <asyncio-date-coroutine>` example uses a :ref: `coroutine
713+ <coroutine>`.
714+
715+
677716.. _asyncio-watch-read-event :
678717
679718Watch a file descriptor for read events
0 commit comments