Replies: 1 comment 5 replies
-
A passer-by, not a team. First of all, the 'worker' I see in your code is not a real worker, just a background task. Which lives on the same single process as the server. So if you want to gracefully shutdown the server just send a import os
import signal
async def worker(app):
try:
while True:
await asyncio.sleep(1)
app.state.shared_state["value"] += 1
print("Worker incremented value")
# raise ValueError # simulates a crash
except asyncio.CancelledError:
print("Worker stopped cleanly")
except Exception as exc:
print(f"Worker crashed: {exc}")
# shutdown
os.kill(os.getpid(), signal.SIGINT)
async def lifespan(app):
app.state.shared_state = {"value": 0}
app.state.worker_task = asyncio.create_task(worker(app))
try:
yield
finally:
app.state.worker_task.cancel() # always stop 'worker'
await app.state.worker_task |
Beta Was this translation helpful? Give feedback.
5 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hello team 👋
Problem
I want to launch a background worker in Starlette that shares the same state and event loop as the main application. My goal is to process messages both from the Starlette API and a worker queue using the same logic and shared state. Launching a separate process is not an option, as I need to share state and logic. (And also due to company microservices guidelines...)
I tried launching an async worker inside the application's lifespan event, but encountered many issues related to handling the worker lifecycle, especially stopping everything cleanly when the worker crashes.
Minimal Example
Question
What is the recommended approach for running a background task like this in Starlette, ensuring that it shares the same event loop and state as the main application? How should the worker lifecycle (especially crash handling and stopping everything cleanly) be managed?
A different approach would be launching the worker first and letting it manages starlette and not the opposite?
Any advice or examples or suggestions of new approaches would be appreciated!
Thank you.
Beta Was this translation helpful? Give feedback.
All reactions