-
How can I add permanently running background tasks? I want to have the following behaviour:
Exampleimport time
import uvicorn
from fastapi import FastAPI
app = FastAPI()
def main():
# where and how should i start this function
value = 0
while True:
time.sleep(0.1)
value += 1
@app.get("/")
def root():
# how can i read value from main?
return value
if __name__ == "__main__":
uvicorn.run("api:app", host="0.0.0.0", port=8001, reload=True) |
Beta Was this translation helpful? Give feedback.
Replies: 12 comments 4 replies
-
@tweakimp hello! But don't add your main function directly, cause it will run forever. If you consider using of asyncio (and understand async as general concept) you can try something like this:
|
Beta Was this translation helpful? Give feedback.
-
Thank you for your fast answer, this works really well. I can even set the value from another end point: @app.get("/set_value")
def set_value(x: int):
runner.value = x
return f"set runner.value to {x}" |
Beta Was this translation helpful? Give feedback.
-
This issue can be set to |
Beta Was this translation helpful? Give feedback.
-
The flag is attached when @tiangolo answers 😄 |
Beta Was this translation helpful? Give feedback.
-
Thanks for the help here @insomnes and @Kludex ! 👏 🙇 Thanks for reporting back and closing the issue @tweakimp 👍 Hehe, I add the
|
Beta Was this translation helpful? Give feedback.
-
I followed this example but instead I setup a Kafka consumer that was supposed to read messages from a topic. The problem is that I'm getting worker timeout. And the server just restarts.
And this is my start-up event
At first it works and reads the messages from my topic, but then it just crashes the workers |
Beta Was this translation helpful? Give feedback.
-
You run sync code inside async loop. |
Beta Was this translation helpful? Give feedback.
-
@OctaM Have you figured out a way to solve this, and run your Kafka consumer with a background task? |
Beta Was this translation helpful? Give feedback.
-
thanks for the answers. it works well in development env. |
Beta Was this translation helpful? Give feedback.
-
@bingblackbean Try using some non-blocking lock such as linux lock(fcntl.flock) if your app is running on a single server or use redis SETNX(to have a single worker across all servers) to tell other background workers to exit. something like-
|
Beta Was this translation helpful? Give feedback.
-
you can use |
Beta Was this translation helpful? Give feedback.
-
You might find #10743 helpful |
Beta Was this translation helpful? Give feedback.
@tweakimp hello!
Maybe you can use on startup event functionality:
https://fastapi.tiangolo.com/advanced/events/
But don't add your main function directly, cause it will run forever.
Maybe you can do it with starting daemon thread of main() in some startup function.
If you consider using of asyncio (and understand async as general concept) you can try something like this: