File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Lifaspan tasks in PyNest
2
+
3
+ ## Introduction
4
+
5
+ Lifespan tasks - coroutines, which run while app is working.
6
+
7
+ ## Defining a lifespan task
8
+ As example of lifespan task will use coroutine, which print time every hour. In real user cases can be everything else.
9
+
10
+ ``` python
11
+ import asyncio
12
+ from datetime import datetime
13
+
14
+ async def print_current_time ():
15
+ while True :
16
+ current_time = datetime.now().strftime(" %H:%M:%S" )
17
+ print (f " Current time: { current_time} " )
18
+ await asyncio.sleep(3600 )
19
+ ```
20
+
21
+ ## Implement a lifespan task
22
+ In ` app_module.py ` we can define a startup handler, and run lifespan inside it
23
+
24
+ ``` python
25
+ from nest.core import PyNestFactory
26
+
27
+ app = PyNestFactory.create(
28
+ AppModule,
29
+ description = " This is my PyNest app with lifespan task" ,
30
+ title = " My App" ,
31
+ version = " 1.0.0" ,
32
+ debug = True ,
33
+ )
34
+
35
+ http_server = app.get_server()
36
+
37
+ @http_server.on_event (" startup" )
38
+ async def startup ():
39
+ await print_current_time()
40
+ ```
41
+
42
+ Now ` print_current_time ` will work in lifespan after startup.
You can’t perform that action at this time.
0 commit comments