Internal hooks

In practice, it is useful to be able to perform some actions before the microagent starts working or after it stops. For this aim there are internal hooks that allow you to run methods on pre_start, post_start, and pre_stop.

pre_start - is called before the microagent is ready to accept events and consume messages. This ensures that handlers will be called when already connections established with other services - databases, mail, logs; initialized caches, objects, and so on.

post_start - called when the microagent has already started accepting events and messages. It is can be useful for sending notifications to monitoring service and etc.

pre_stop - called when the microagent go shutdown. It can be useful for sending notifications to the monitoring service, and so on.

server - “run forever” handler. If it crashes with exception microagent will be stopped. If you are using a launcher from the library and server run forever, it is important correctly to stop the servers with ServerInterrupt exception.

In addition, there is a special mechanism for running nested services. Methods marked with the server decorator will be started in “run forever” mode. It’s allow provide endpoints for microagent, such as http, websocket, smtp or other.

microagent.on(label: str) Callable[[Callable[[Any], Awaitable[None]]], Callable[[Any], Awaitable[None]]][source]

Hooks for internal events (pre_start, post_start, pre_stop) or running forever servers (server).

Server-function will be call as run-forever asyncio task.

Parameters:

label – Hook type label string (pre_start, post_start, pre_stop, server)

@on('pre_start')
async def handler_1(self):
    log.info('Called handler 1')

@on('post_start')
async def handler_2(self):
    log.info('Called handler 2')

@on('pre_stop')
async def handler_3(self):
    log.info('Called handler 3')

@on('server')
async def run_server(self):
    await Server().start()  # run forever
    raise ServerInterrupt('Exit')  # graceful exit