Skip to content

Commit

Permalink
Fix periodic async callbacks (#6053)
Browse files Browse the repository at this point in the history
* Do not resolve references on PeriodicCallback

* Add tests
  • Loading branch information
philippjfr committed Dec 15, 2023
1 parent f639c2e commit ecaeb0f
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
11 changes: 7 additions & 4 deletions panel/io/callbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

from ..util import edit_readonly, function_name
from .logging import LOG_PERIODIC_END, LOG_PERIODIC_START
from .state import curdoc_locked, state
from .state import curdoc_locked, set_curdoc, state

log = logging.getLogger('panel.callbacks')
_periodic_logger = logging.getLogger(f'{__name__}.PeriodicCallback')
Expand All @@ -29,7 +29,7 @@ class PeriodicCallback(param.Parameterized):
the running parameter to True or False respectively.
"""

callback = param.Callable(doc="""
callback = param.Callable(allow_refs=False, doc="""
The callback to execute periodically.""")

counter = param.Integer(default=0, doc="""
Expand Down Expand Up @@ -79,7 +79,6 @@ def _update_period(self):
self.start()

def _exec_callback(self, post=False):
from .state import set_curdoc
try:
with set_curdoc(self._doc):
if self.running:
Expand Down Expand Up @@ -129,7 +128,11 @@ async def _periodic_callback(self):
try:
cb = self._exec_callback()
if inspect.isawaitable(cb):
await cb
if self._doc:
with set_curdoc(self._doc):
await cb
else:
await cb
except Exception:
log.exception('Periodic callback failed.')
raise
Expand Down
17 changes: 17 additions & 0 deletions panel/tests/test_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,23 @@ def test_server_session_info():
assert state.session_info['live'] == 0


def test_server_periodic_async_callback(threads, port):
counts = []

async def cb(count=[0]):
counts.append(count[0])
count[0] += 1

def app():
button = Button(name='Click')
state.add_periodic_callback(cb, 100)
return button

serve_and_request(app)

wait_until(lambda: len(counts) >= 5 and counts == list(range(len(counts))))


def test_server_schedule_repeat():
state.cache['count'] = 0
def periodic_cb():
Expand Down

0 comments on commit ecaeb0f

Please sign in to comment.