Best Practice for Running Background Tasks on Page Load #4053
Answered
by
rodja
patrickwasp
asked this question in
Q&A
-
QuestionI have a NiceGUI app where I need to run a CPU-intensive task when a page loads, without blocking the UI. Here's my current solution using ui.timer: import time
from nicegui import run, ui
def heavy_computation(work_length: int):
time.sleep(work_length)
return "Done!"
class PageExample:
def __init__(self, work_length: int) -> None:
self.work_length = work_length
def create(self):
ui.label(f"Hello World, work length: {self.work_length}")
with ui.tabs().classes("w-full") as tabs:
one = ui.tab("One")
two = ui.tab("Two")
with ui.tab_panels(tabs, value=two).classes("w-full"):
with ui.tab_panel(one):
ui.label("First tab")
with ui.tab_panel(two):
ui.label("Second tab")
self.spinner = ui.spinner(size="lg")
self.spinner.visible = False
ui.timer(0, self.run_heavy_computation, once=True)
async def run_heavy_computation(self):
print("Running heavy computation")
self.spinner.visible = True
result = await run.cpu_bound(heavy_computation, work_length=self.work_length)
self.spinner.visible = False
ui.notify(result)
@ui.page("/{work_length}")
def index_page(work_length: int):
example_page = PageExample(work_length=work_length)
example_page.create()
ui.run() While this works, I'm wondering if using ui.timer(0, ...) is the best practice for running background tasks on page load. |
Beta Was this translation helpful? Give feedback.
Answered by
rodja
Dec 1, 2024
Replies: 1 comment
-
There is an undocumented module from nicegui import ui, background_tasks
def heavy_computation():
time.sleep(2)
@ui.page('/')
def index():
async def compute():
await run.cpu_bound(heavy_computation)
spinner.visible = False
spinner = ui.spinner()
background_tasks.create(compute())
ui.run() |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
patrickwasp
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There is an undocumented module
background_tasks
in NiceGUI: