Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 39 ยท Projects and Practice

Project: A Live System Monitor with Tauri

Build a live CPU and memory monitor with Tauri 2: a Rust background task, the sysinfo crate, events versus channels, start and stop commands, a ring buffer and a text chart, with runnable models.

The notes app was request and response: the frontend asks, Rust answers. Many desktop apps are different. A system monitor, a download manager, a log viewer or a chat client has data that arrives over time, and Rust must push it to the UI. In this project you build a live monitor of CPU and memory use, and learn the Tauri tools for streaming: background tasks, events, channels, and clean shutdown.

You will use ideas from Writing a Custom Plugin (managed state, events) and the testing style from Testing Tauri Apps.

Real versus stand-in. The toml, rust and ts blocks are real Tauri 2 code. Reading real CPU numbers needs the operating system, so the runnable blocks use a fake sampler with a seeded random generator to demonstrate the logic: ring buffer, smoothing, throttling and a text chart.

What we are building

  • A background task samples CPU and memory once per second.
  • The task sends each sample to the frontend, which draws a live chart.
  • Start and Stop buttons control it; closing the window stops it.
  • The chart keeps the last 60 samples, never more, so memory stays flat.

Events versus channels

Tauri has two ways to push data to the frontend:

Events Channels
API app.emit("name", payload) and listen("name") A Channel<T> passed to a command as an argument
Delivery Broadcast to any listener, by name Directed to the one caller, ordered
Speed Fine for small, occasional messages (JSON) Built for fast, ordered streams (progress, logs, samples)
Good for "settings changed", "download finished" "here are 60 samples per second"

Use events for notifications that several parts of the UI may care about, and channels for streams that belong to one request.

Rust: the sampler with a channel

Add the dependency:

TOML
# src-tauri/Cargo.toml
[dependencies]
sysinfo = "0.33"
tokio = { version = "1", features = ["time", "sync"] }

Managed state holds the handle that lets us stop the task:

Rust
use serde::Serialize;
use std::sync::Mutex;
use sysinfo::System;
use tauri::{ipc::Channel, State};
use tokio::{sync::oneshot, time::{interval, Duration}};

#[derive(Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Sample {
    pub cpu_percent: f32,
    pub used_memory_mb: u64,
    pub total_memory_mb: u64,
}

#[derive(Default)]
pub struct Monitor(Mutex<Option<oneshot::Sender<()>>>);

#[tauri::command]
pub fn start_monitor(state: State<'_, Monitor>, on_sample: Channel<Sample>) -> Result<(), String> {
    let mut slot = state.0.lock().map_err(|_| "state poisoned")?;
    if slot.is_some() {
        return Err("monitor already running".into());
    }
    let (stop_tx, mut stop_rx) = oneshot::channel::<()>();
    *slot = Some(stop_tx);

    tauri::async_runtime::spawn(async move {
        let mut sys = System::new();
        let mut tick = interval(Duration::from_secs(1));
        loop {
            tokio::select! {
                _ = &mut stop_rx => break,           // stop requested
                _ = tick.tick() => {
                    sys.refresh_cpu_usage();
                    sys.refresh_memory();
                    let sample = Sample {
                        cpu_percent: sys.global_cpu_usage(),
                        used_memory_mb: sys.used_memory() / 1_048_576,
                        total_memory_mb: sys.total_memory() / 1_048_576,
                    };
                    if on_sample.send(sample).is_err() {
                        break; // the frontend went away
                    }
                }
            }
        }
    });
    Ok(())
}

#[tauri::command]
pub fn stop_monitor(state: State<'_, Monitor>) {
    if let Some(stop) = state.0.lock().unwrap().take() {
        let _ = stop.send(());
    }
}

Three design points deserve attention:

  1. Never block a command. spawn returns immediately and the loop runs in the background; a command that loops forever would freeze its thread.
  2. A stop signal. The oneshot channel lets stop_monitor end the loop cleanly. select! waits for either the next tick or the stop.
  3. The frontend disappearing is normal. send returns an error when the window closed, which ends the task instead of leaking it. Register Monitor::default() with .manage(...) and add both commands to generate_handler!.

CPU usage needs two refreshes some time apart to be meaningful, which is why the loop keeps one System alive between ticks instead of creating a new one every time.

The frontend

TypeScript
import { invoke, Channel } from '@tauri-apps/api/core';

type Sample = { cpuPercent: number; usedMemoryMb: number; totalMemoryMb: number };

const samples: Sample[] = [];

export async function start(onChange: (s: Sample[]) => void) {
  const channel = new Channel<Sample>();
  channel.onmessage = (sample) => {
    samples.push(sample);
    if (samples.length > 60) samples.shift(); // keep only the last minute
    onChange(samples);
  };
  await invoke('start_monitor', { onSample: channel });
}

export const stop = () => invoke('stop_monitor');

Notice the argument name: Rust's on_sample becomes onSample in JavaScript, because Tauri converts command argument names to camelCase.

The logic you can run

This block simulates the stream: a ring buffer, a moving average to smooth jumpy numbers, and a text sparkline chart. The fake sampler uses a seeded generator so the output is the same every time.

Node.js Core model: ring buffer, smoothing and text chart

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Throttling: do not redraw faster than the eye can see

If a source sends 1000 samples per second, redrawing a chart for each one wastes battery. Two common fixes are to batch in Rust (send an array every 100 ms) or to throttle drawing in the frontend with requestAnimationFrame. This model counts how many redraws happen when 500 messages arrive within about one second and drawing is limited to every 100 ms.

Node.js Core model: throttle redraws

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Shutting down cleanly

  • Stop the task when the window closes: listen for the window's close event in Rust (on_window_event) and call the same stop logic, or rely on the failing send as above.
  • Handle double start (the guard in start_monitor) and stop when not running (a no-op).
  • Test the logic: a Rust unit test can feed samples into the ring buffer function; a frontend test can use mockIPC to return nothing and then push messages through a fake channel.

Extensions

  • Per-process list with sys.processes(), sorted by CPU, refreshed every few seconds.
  • A tray icon that shows the current load, with a menu to start and stop (menus and tray are covered earlier in this track).
  • Thresholds: send a notification when CPU stays above 90% for a minute (notifications).
  • Persist the history to SQLite and draw a daily chart (storage).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which Tauri mechanism suits a fast, ordered stream of samples for one caller?

    Channels are designed for ordered streaming to the caller that created them; events broadcast by name.
  2. 2. Why does the sampler loop run in a spawned task instead of inside the command body?

    Long-running work must not block the command; spawn the work and return.
  3. 3. What should the task do when channel.send fails?

    A failed send means nobody listens; ending the task prevents leaked background work.
  4. 4. Why keep only the last 60 samples in the frontend?

    A bounded buffer stops an endless stream from growing memory without limit.

Summary

  • Use channels for ordered streams to one caller and events for named notifications.
  • Spawn a background task, give it a stop signal, and end it when the frontend disappears.
  • Bound the data (ring buffer), smooth noisy values and throttle redraws.
  • Keep logic in small testable pieces, then add tray, alerts and persistence as extensions.

Next: Project: A Clipboard History Manager