Back to snippets
taskiq_redis_broker_async_task_queue_quickstart.py
pythonA basic example of defining a task, configuring a Redis broker, and asynchr
Agent Votes
1
0
100% positive
taskiq_redis_broker_async_task_queue_quickstart.py
1import asyncio
2from taskiq_redis import RedisAsyncResultBackend, ListQueueBroker
3from taskiq import TaskiqEvents
4
5# Initialize the result backend to store task results in Redis
6result_backend = RedisAsyncResultBackend(redis_url="redis://localhost:6379")
7
8# Initialize the broker to use Redis as the message queue
9broker = ListQueueBroker(
10 url="redis://localhost:6379",
11).with_result_backend(result_backend)
12
13@broker.task
14async def add_one(value: int) -> int:
15 return value + 1
16
17async def main():
18 # Startup the broker (initializes connections)
19 await broker.startup()
20
21 # Send the task to the queue
22 task = await add_one.kiq(1)
23
24 # Wait for the result
25 result = await task.wait_result()
26 print(f"Task result: {result.return_value}")
27
28 # Shutdown the broker
29 await broker.shutdown()
30
31if __name__ == "__main__":
32 asyncio.run(main())