Tokio
Tauri offers a Tokio runtime by default. Here are some common things you’ll need to know how to do in order to use Tokio effectively in Tauri.
In most projects this part is unnecessary because you only need the capabilities from Tokio that Tauri re-exports in tauri::async_runtime
. However, if you need more advanced functionalities from the broader Tokio ecosystem there’s absolutely nothing wrong with adding it directly.
cargo add tokio
async fn setup(app: AppHandle) { // Do your async setup here instead}
fn main() { Builder() .setup(|app| { tauri::async_runtime::block_on(setup(app.handle())); })}
In order to spawn a background thread in Tauri all you have to do is use tauri::async_runtime::spawn()
. This will schedule an async function to be executed by one of the Tokio runtimes worker threads.
async fn my_daemon() { loop { println!("I run in the background!"); tokio::time::sleep(tokio::time::Duration::from_secs(1)).await; }}
fn main() { Builder() .setup(|app| { tauri::async_runtime::spawn(my_daemon()); })}