From 100d2d0d25853d9866cde238f48f720d99ec03cd Mon Sep 17 00:00:00 2001 From: Joe Cheng Date: Thu, 3 Aug 2023 22:30:44 -0700 Subject: [PATCH] Make model score app work on Connect/Shinyapps.io --- examples/model-score/scoredata.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/examples/model-score/scoredata.py b/examples/model-score/scoredata.py index 4e595fe72..11613c4da 100644 --- a/examples/model-score/scoredata.py +++ b/examples/model-score/scoredata.py @@ -55,4 +55,16 @@ async def update_db(position): def begin(): position = init_db() - asyncio.create_task(update_db(position)) + + # After initializing the database, we need to start a non-blocking task to update it + # every second or so. If an event loop is already running, we can use an asyncio + # task. (This is the case when running via `shiny run` and shinylive.) Otherwise, we + # need to launch a background thread and run an asyncio event loop there. (This is + # the case when running via shinyapps.io or Posit Connect.) + + if asyncio.get_event_loop().is_running(): + asyncio.create_task(update_db(position)) + else: + from threading import Thread + + Thread(target=lambda: asyncio.run(update_db(position)), daemon=True).start()