Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix periodic async callbacks #6053

Merged
merged 2 commits into from
Dec 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading