Background services

There are cases where you need to run code in parallel of your application, for example, to listen to a messaging queue.

Zayt provides the zayt.web.background decorator to mark functions to be run in background as async tasks alongside the main application.

from zayt.web import background


@background
async def background_service():
    ...

Background service functions can receive services as parameters from the dependency injection system.

For example, you can create a function that listens for notification from Redis:

import structlog
from redis.asyncio import Redis
from zayt.web import background

logger = structlog.get_logger(__name__)


@background
async def listen_channel(redis: Redis):
    async with redis.pubsub() as pubsub:
        await pubsub.psubscribe("chat")
        while True:
            message = await pubsub.get_message(
                ignore_subscribe_messages=True,
                timeout=None
            )
            if message:
                logger.info(
                    "chat message",
                     value=message["data"].decode(),
                 )