Simple example for starting/stopping a (background) task with nicegui #5030
Replies: 1 comment 3 replies
-
Hi @malleite2025, In order to avoid CPU-bound tasks blocking the main UI thread, you need to run them on a separate process. This can be done using NiceGUI's import time
from multiprocessing import Manager, Queue
from nicegui import run, ui
def calculate(ctrl_q: Queue) -> None:
while ctrl_q.empty() or ctrl_q.get_nowait() != 'STOP':
print('calculating...')
time.sleep(0.5)
@ui.page('/')
def main_page():
manager = Manager()
ctrl_q = manager.Queue()
async def start() -> None:
await run.cpu_bound(calculate, ctrl_q)
def stop() -> None:
ctrl_q.put('STOP')
ui.button('start', on_click=start)
ui.button('stop', on_click=stop)
ui.run() |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
First Check
Example Code
Description
Hi,
I am struggling a bit trying to have a very simple application where a "start" button starts a background task to do some work continuously and a "stop" button stops this task . I understand I should use asyncio otherwise the task blocks the execution of the gui (as happens with the attached code) , but I am not being able to make it work. Is there a similar example on how to do this correctly ? Thank you
NiceGUI Version
2.21.1
Python Version
3.13
Browser
Chrome
Operating System
Linux
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions