run async function in an endless loop #3067
Answered
by
falkoschindler
v479038280
asked this question in
Q&A
-
Questionhow to make async handler run in an endless loop, import asyncio
from nicegui import ui
async def async_task():
ui.notify('Asynchronous task started')
await asyncio.sleep(5)
ui.notify('Asynchronous task finished')
ui.button('start async task', on_click=async_task)
ui.run() |
Beta Was this translation helpful? Give feedback.
Answered by
falkoschindler
May 13, 2024
Replies: 1 comment
-
Hi @v479038280, You can start any async function using async def loop():
while True:
await async_task()
app.on_startup(loop) You could also use a ui.timer(1.0, async_task) # runs immediately as part of the auto-index page
@ui.page('/timer')
async def timer_page():
ui.timer(1.0, async_task) # runs per client connection on /timer |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
v479038280
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @v479038280,
You can start any async function using
app.on_startup
:You could also use a
ui.timer
. Note that this acts like a UI element: When used in global scope (i.e. on the auto-index page), it runs immediately. But when used in a@page
function, it only runs when somebody visits that page: