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

I can’t seem to find any information on this anywhere: What exactly does the Stop button do, hat shows up while a task is running?

I have a time consuming task (3-5h) that can be started via streamlit. If the user has to end the process for some reason (progress is cached so it can be continued at any time), the stop button in the top right corner does the trick. However, that isn’t exactly a graceful shutdown.

Now I’m wondering if it’s at all possible to handle the event of the stop button being pressed?
I’m thinking of something similar to a keyboard interrupt that can be handled with try/catch in regular python.

Any help or pointers to more information would be appreciated!

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.

@asehmi thank you for your tip!

At first thought I’m thinking this is a bit overkill for my usecase - in any case it depends on where I want to go with my application.
But I’ll definitely consider it.

@BalduinLandolt It’s not as bad as it sounds :wink:

I’ve created a simple implementation here: