Execute code when Background Callback is canceled

Hi fellas,

I’m using the new Background Callbacks, with the feature of canceling. It is possible to trigger some function or code when the callback is cancelled?

I’m debugging the callback, but nothing is fired when is cancelled. I’m using the next example available in the documentation:

import time
import os

import dash
from dash import DiskcacheManager, CeleryManager, Input, Output, html

if 'REDIS_URL' in os.environ:
    # Use Redis & Celery if REDIS_URL set as an env variable
    from celery import Celery
    celery_app = Celery(__name__, broker=os.environ['REDIS_URL'], backend=os.environ['REDIS_URL'])
    background_callback_manager = CeleryManager(celery_app)

else:
    # Diskcache for non-production apps when developing locally
    import diskcache
    cache = diskcache.Cache("./cache")
    background_callback_manager = DiskcacheManager(cache)

app = dash.Dash(__name__, background_callback_manager=background_callback_manager)

app.layout = html.Div(
    [
        html.Div([html.P(id="paragraph_id", children=["Button not clicked"])]),
        html.Button(id="button_id", children="Run Job!"),
        html.Button(id="cancel_button_id", children="Cancel Running Job!"),
    ]
)

@dash.callback(
    output=Output("paragraph_id", "children"),
    inputs=Input("button_id", "n_clicks"),
    background=True,
    running=[
        (Output("button_id", "disabled"), True, False),
        (Output("cancel_button_id", "disabled"), False, True),
    ],
    cancel=[Input("cancel_button_id", "n_clicks")],
)
def update_clicks(n_clicks):
    time.sleep(2.0)
    return [f"Clicked {n_clicks} times"]


if __name__ == "__main__":
    app.run_server(debug=True)

If there is not, I think that is a MUST.

Hello @jeffresh,

Not necessarily sure that this is a must, because right now their cancel is associated with a specific event, the button push. This can be used to determine that the callback was cancelled through another callback.

However, if you were to want to know exactly about the event cancellation, you should be able to look at the post requests to the server. Because this is what tells the server to stop the process and the requests going from the client.

The easiest way to do this would be to look in the network tab at the post request to _dash-update-component.

1 Like

Yes, that’s my case. The callback trigger some async task that interact with some services (like bd). So I need to interrupt it and execute some code, cleaning the interaction effects at that moment. Ty for the tip, I will dig in to it.

I think that in the same way we got the “progress, set_progress”, could be interesting got a “cancel, set_cancel” integrated in the same way, firing the cancel task in the “same context”.

For simple tasks, you can implement it as another callback with the cancel button as an Input, exactly as you said.

2 Likes