Background Executor
The background executor allows you to spawn asynchronous tasks onto background threads.
Accessing the Background Executor
The background_executor returns a reference to the platform BackgroundExecutor.
use gpui::{AppContext, Application};
fn main() {
Application::new().run(|app| {
let background_executor = app.background_executor();
});
}
Spawn
The spawn function takes a Future and enqueues it to run on a background thread, a Task<T> is returned. When this task is dropped it will be cancelled immediatley. Using detach on a Task<T> allows it to run to completion.
use gpui::Application;
fn main() {
Application::new().run(|app| {
app.background_executor()
.spawn(async {
// Some asynchronous work
})
.detach();
});
}
Timer
The timer function takes a Duration and returns a Task<()> that will complete after the elapsed duration. This task can then be awaited in a future.
use std::time::Duration;
use gpui::Application;
fn main() {
Application::new().run(|app| {
let timer = app.background_executor().timer(Duration::from_secs(10));
app.background_executor()
.spawn(async {
timer.await;
println!("Timer Finished!");
})
.detach();
});
}