Running async periodic callback

Hello! I have been using bokeh for quite some time now but wanted to move to panel given the large amount of visual tools. I have been relying heavily on the async capabilities of bokeh and now I am struggling with replicating some behaviours in Panel.

Following this tutorial Async and Concurrency — Panel 0.13.0a5 documentation I managed to get an async callback on button click working. The note below says I should be able to also run an async callback using pn.state.add_periodic_callback. I have tried that as in the example below but the async function doesn’t seem to be called. Am I missing something? Code is being run in jupyter.

import panel as pn
import asyncio
pn.extension()

text = pn.widgets.StaticText(value="test")

async def test():
    print("halo")
    text.value = "halo"
    await asyncio.sleep(1)
    text.value = "halo2"

pn.state.add_periodic_callback(test, period=2000)
pn.Row(text).servable()

Hi @Kadek

Welcome to the community. Great question. According to https://github.com/tornadoweb/tornado/issues/2828#issuecomment-605059750 you can run it like

pn.state.add_periodic_callback(lambda: asyncio.create_task(test()), period=2000)

import panel as pn
import asyncio
import datetime
pn.extension()

text = pn.widgets.StaticText(value="")

async def test():
    text.value = str(datetime.datetime.now()) + " start"
    await asyncio.sleep(1)
    text.value = str(datetime.datetime.now()) + " finish"

pn.state.add_periodic_callback(lambda: asyncio.create_task(test()), period=2000)
pn.Row(text).servable()![async|video](upload://wLrv8Vtr3F8ZvY8OiQnTRAQ34vx.mp4)

1 Like

I’ve reported this as a bug here pn.state.add_periodic_callback does not support async functions · Issue #2736 · holoviz/panel (github.com)

Thank you so much! That works! Happy to join such an active community!

3 Likes

Great to hear.

If you have some concrete async code examples to share please do. We don’t have some many in the community forum yet. So it will help build the knowledge base and inspire us all. Thanks.

1 Like