Gracefully end Task Execution / How does the Stop Button work?

This is quite tricky to do in Streamlit due to its execution model and Python’s GIL. I released an app which uses a FastAPI wrapper for my “long running” process. The approach I took is:

  • Launch the FastAPI wrapper as a separate process from a thread in Streamlit
  • Start the long running process thread in the FastAPI initializer or kick it off behind a route, e.g. /run which would be more flexible and should be called via a web request from Streamlit
  • Create a /shutdown route which kills its own process, and hence the long running child process thread
  • From Streamlit call /shutdown to stop the long running process

The benefit of doing it this way is to avoid deploying multiple separate server apps, one being Streamlit and the other being my “long-running” process.

Hope this helps, but note the solution is only suited for “local” use… i.e. if your Streamlit app is going to be deployed and used by multiple users, then you’d be better off deploying your long running process as a separate standalone web service, if possible.