How to programmatically stop dash app gracefully?

Have a dash app develped using python on VSCode + Jupyter.
Wish to stop the app, after task is done. I have tried…
a) def stop_execution():
subprocess.run([“jupyter”, “notebook”, “stop”, “all”])
b) pid = os.getpid()
os.kill(pid, signal.SIGINT)
Option b) does the job, but abrupt closing message and kernel dies…
Manually clicking stop execution button on VS Code works,but
Am sure there has to be some way (or may be JS) to stop execution programmatically.

(Am laughing at myself, thinking of a joke wherein a person rides bike without knowing how to stop…Someone please help me quick before I crash!!) Cheers.

Hello @mmm2310,

Welcome to the community!

You could try to use a supervisor instead. And then the supervisor is easy to control from the command line, or inside an app, etc.

Thanks for your reply. Sorry, but I have not used Supervisor earlier. Please help me with any similar use case in Python. Thanks again.

One update. Am using Windows. Just searched documentation for supervisor and learnt it is meant for UNIX and MacOS…but, " Supervisor will not run at all under any version of Windows". I guess, Supervisor is what os.kill or SIGINT are meant to do…but it causes abrupt end.
Any other method to gracefully exit dash app programmatically ??

Good day,
I found a solution to gracefully exit dash app. For the benefit of others, am posting code snippet here…

def stop_execution():
    global keepPlot
    #stream.stop_stream()
    keepPlot=False
    # stop the Flask server
    server.shutdown()
    server_thread.join()
    print("Dash app stopped gracefully.")
    
    
server = Flask(__name__)
app = Dash(__name__, server=server)


if __name__ == "__main__":
    # create a server instance
    server = make_server("localhost", 8050, server)
    # start the server in a separate thread
    server_thread = threading.Thread(target=server.serve_forever)
    server_thread.start()

    # start the Dash app in a separate thread
    def start_dash_app():
        app.run_server(debug=True, use_reloader=False)

    dash_thread = threading.Thread(target=start_dash_app)
    dash_thread.start()

    while keepPlot:
        time.sleep(1)  # keep the main thread alive while the other threads are running

Trick is to run app in two separate threads…and run stop_execution() when u wish to stop execution.

Thanks and have a nice day.

Hello @mmm2310,

Glad you got something that works, and thank you for posting what works in your case.

Dash is stateless, so, typically needing to save graphs, etc is unnecessary because everything is normally with the client’s interface.

This is what allows multiple servers to run.

Is there a benefit to it stopping gracefully vs quitting the service running it?