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:


2 Likes