pub trait Task:
Sized
+ Send
+ 'static {
type Output: Send + 'static;
// Required method
fn run(self) -> impl Future<Output = Self::Output> + Send;
}Expand description
A trait defining an asynchronously executable unit of work.
Implement this trait for any struct that represents a task for the TaskExecutor to run.
The run method contains the core logic of the task and is executed asynchronously.
§Associated Types
Output: The type of the value that the task will produce upon successful completion.
§Type Constraints
Sized + Send + 'static: Ensures the task can be owned, moved between threads, and has a lifetime that spans the entire program duration.Output: Send + 'static: Ensures the task’s result can also be safely sent across threads.
§Example
use mini_executor::{TaskExecutor, Task};
use tokio::runtime::{Runtime, Builder};
use tokio::time::{sleep, Duration};
use std::sync::OnceLock;
// 1. Define the task struct.
struct MySimpleTask {
id: u32,
}
// 2. Implement the `Task` trait for it.
impl Task for MySimpleTask {
type Output = String;
async fn run(self) -> Self::Output {
sleep(Duration::from_millis(10)).await;
format!("Task {} finished", self.id)
}
}
// 3. Execute it using a TaskExecutor.
static RT: OnceLock<Runtime> = OnceLock::new();
fn main() -> Result<(), Box<dyn std::error::Error>> {
let rt = RT.get_or_init(|| {
Builder::new_current_thread()
.enable_time() // Enable timers for `sleep`
.build()
.unwrap()
});
let executor = TaskExecutor::new(rt);
let result = rt.block_on(async {
executor.execute_waiting(MySimpleTask { id: 1 }).await
})?;
assert_eq!(result, "Task 1 finished");
println!("{}", result);
Ok(())
}Required Associated Types§
Required Methods§
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".