From ce7d0d52e3f01f3a5dada421daf965057c941f40 Mon Sep 17 00:00:00 2001 From: ilya Date: Thu, 20 Mar 2025 21:52:57 +0300 Subject: [PATCH 1/2] https://github.com/PythonNest/PyNest/issues/105 --- docs/lifespan_tasks.md | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 docs/lifespan_tasks.md diff --git a/docs/lifespan_tasks.md b/docs/lifespan_tasks.md new file mode 100644 index 0000000..7000c60 --- /dev/null +++ b/docs/lifespan_tasks.md @@ -0,0 +1,42 @@ +# Lifaspan tasks in PyNest + +## Introduction + +Lifespan tasks - coroutines, which run while app is working. + +## Defining a lifespan task +As example of lifespan task will use coroutine, which print time every hour. In real user cases can be everything else. + +```python +import asyncio +from datetime import datetime + +async def print_current_time(): + while True: + current_time = datetime.now().strftime("%H:%M:%S") + print(f"Current time: {current_time}") + await asyncio.sleep(3600) +``` + +## Implement a lifespan task +In `app_module.py` we can define a startup handler, and run lifespan inside it + +```python +from nest.core import PyNestFactory + +app = PyNestFactory.create( + AppModule, + description="This is my FastAPI app with lifespan task", + title="My App", + version="1.0.0", + debug=True, +) + +http_server = app.get_server() + +@http_server.on_event("startup") +async def startup(): + await print_current_time() +``` + +Now `print_current_time` will work in lifespan after startup. From 793812e4e39f7edbc96883b55c19d377701e5611 Mon Sep 17 00:00:00 2001 From: ilya Date: Thu, 20 Mar 2025 21:58:29 +0300 Subject: [PATCH 2/2] https://github.com/PythonNest/PyNest/issues/105 --- docs/lifespan_tasks.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/lifespan_tasks.md b/docs/lifespan_tasks.md index 7000c60..f71a6aa 100644 --- a/docs/lifespan_tasks.md +++ b/docs/lifespan_tasks.md @@ -26,7 +26,7 @@ from nest.core import PyNestFactory app = PyNestFactory.create( AppModule, - description="This is my FastAPI app with lifespan task", + description="This is my PyNest app with lifespan task", title="My App", version="1.0.0", debug=True,