How to turn system monitor script into a app? #2245
-
Hi, I'm new to wave and started running some of the tutorials but I'm stuck with turning a script into a app. The script in question is the system_monitor example. How can I turn this into a non blocking app? Any help will be appreciated. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
cc @marek-mihok |
Beta Was this translation helpful? Give feedback.
-
The answer lies in unblocking Screen.Recording.2024-03-20.at.17.22.37.movimport psutil
from h2o_wave import main, app, Q, ui, data
async def monitor_cpu(q: Q):
while True:
await q.sleep(1)
cpu_usage = psutil.cpu_percent()
q.page['monitor'].value = cpu_usage
q.page['monitor'].data.usage = cpu_usage
q.page['monitor'].plot_data[-1] = [q.client.tick, cpu_usage]
q.client.tick += 1
await q.page.save()
@app('/monitor')
async def serve(q: Q):
if not q.client.initialized:
q.client.tick = 0
q.client.count = 0
q.page['monitor'] = ui.small_series_stat_card(
box='1 1 1 1',
title='CPU',
value='={{usage}}%',
data=dict(usage=0.0),
plot_data=data('tick usage', -15),
plot_category='tick',
plot_value='usage',
plot_zero_value=0,
plot_color='$red',
)
q.page['counter'] = ui.form_card(box='2 1 2 2', items=[
ui.text(name='text', content=f'Current count: {q.client.count}'),
ui.button(name='increment', label='Increment'),
])
q.client.initialized = True
await monitor_cpu(q)
if q.args.increment:
q.client.count += 1
q.page['counter'].text.content = f'Current count: {q.client.count}'
await q.page.save() If you struggle with unblocking your apps in the future this article by @mturoci may be helpful. |
Beta Was this translation helpful? Give feedback.
-
That's great, thanks. |
Beta Was this translation helpful? Give feedback.
The answer lies in unblocking
psutil.cpu_percent()
by removing itsinterval=1
parameter and using asynchronousq.sleep
instead of synchronoustime.sleep
. You can see it's non-blocking on this counter app:Screen.Recording.2024-03-20.at.17.22.37.mov