asyncio-eventloop.rst 20.4 KB

Base Event Loop

The event loop is the central execution device provided by :mod:`asyncio`. It provides multiple facilities, amongst which:

Base class of event loops.

Run an event loop

Calls

Delayed calls

The event loop has its own internal clock for computing timeouts. Which clock is used depends on the (platform-specific) event loop implementation; ideally it is a monotonic clock. This will generally be a different clock than :func:`time.time`.

Note

Timeouts (relative delay or absolute when) should not exceed one day.

Coroutines

Creating connections

Creating listening connections

Watch file descriptors

Low-level socket operations

Resolve host name

Connect pipes

UNIX signals

Availability: UNIX only.

Executor

Call a function in an :class:`~concurrent.futures.Executor` (pool of threads or pool of processes). By default, an event loop uses a thread pool executor (:class:`~concurrent.futures.ThreadPoolExecutor`).

Error Handling API

Allows to customize how exceptions are handled in the event loop.

Debug mode

Server

Server listening on sockets.

Object created by the :meth:`BaseEventLoop.create_server` method and the :func:`start_server` function. Don't instanciate the class directly.

Handle

A callback wrapper object returned by :func:`BaseEventLoop.call_soon`, :func:`BaseEventLoop.call_soon_threadsafe`, :func:`BaseEventLoop.call_later`, and :func:`BaseEventLoop.call_at`.

Example: Hello World (callback)

Print Hello World every two seconds, using a callback:

import asyncio

def print_and_repeat(loop):
    print('Hello World')
    loop.call_later(2, print_and_repeat, loop)

loop = asyncio.get_event_loop()
loop.call_soon(print_and_repeat, loop)
try:
    loop.run_forever()
finally:
    loop.close()

Example: Set signal handlers for SIGINT and SIGTERM

Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM`:

import asyncio
import functools
import os
import signal

def ask_exit(signame):
    print("got signal %s: exit" % signame)
    loop.stop()

loop = asyncio.get_event_loop()
for signame in ('SIGINT', 'SIGTERM'):
    loop.add_signal_handler(getattr(signal, signame),
                            functools.partial(ask_exit, signame))

print("Event loop running forever, press CTRL+c to interrupt.")
print("pid %s: send SIGINT or SIGTERM to exit." % os.getpid())
try:
    loop.run_forever()
finally:
    loop.close()