How to stop the previous execution on a button click?

Summary

I have created 2 buttons submit and cancel, on submit click, long process gets executed. I need to cancel the execution of the currently running long process on a cancel button click?

Hi @Umang_Gupta

The st.rerun method may be what youโ€™re looking for. Hereโ€™s the Docs page on this:

Hey @dataprofessor , Thanks for the reply.

I have tried with st.rerun as well, but still no luck.

Hi @Umang_Gupta

Can you look into using Session state where the buttons could reset the necessary session state variables so as to start fresh.

@Umang_Gupta

This is a quick example of how to so something similar using callback functions and session state. Please let me know if this helps.

import streamlit as st
import time

if "trigger_execution" not in st.session_state:
    st.session_state["trigger_execution"] = False


def stop_processing():
    st.session_state.clear()


def start_processing():
    st.button("Cancel Execution", on_click=stop_processing)
    st.session_state["trigger_execution"] = True


st.button("Start", on_click=start_processing)
if st.session_state["trigger_execution"]:
    with st.spinner("Processing..."):
        time.sleep(100)
1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.