Calling Aysnc Coroutines from a background callback

I’ve defined a callback with the background=True parameter. My background task originally invoked an async helpers so itself is defined as async, i.e.

async def my_task(*args):
    ids = await get_ids()
    for id in ids:
        data = await get_data(id)

        // do something

    return results

I cannot find any examples where a dash background callback calls and async function. Because the callback cannot be decorated with async I tried using asyncio.run(my_task()) but I’m using polars inside my_task and its blocking - i.e.

@callback(
    output=Output('results-gragh', 'figure'),
    inputs=[
        Input('run-task-button', 'n_clicks'),
    ],
    background=True,
    manager=background_callback_manager,
    prevent_initial_call=True,
    running=[
        (Output("run-task-button", "disabled"), True, False),
    ],
    progress=[Output("progress-bar", "value"), Output("progress-bar", "max")],
    )
def run_background_task(
    set_progress, 
    n_clicks):
    if n_clicks is None:
        raise PreventUpdate

    asyncio.run(my_task())

This hangs on a polars operation that uses the data returned from the api, it works find if I rewrite my_task to avoid the use of async/await. Should this work - i.e. since I cannot await my_task can I use asyncio.run or is there another way of running the task (i.e. can I start it using the background_callback_manager)

I’m using the DiskcacheManager

1 Like