Crate mini_executor

Source
Expand description

§mini_executor

A minimalist, lightweight, and intuitive task execution library for Rust, designed to work seamlessly with the Tokio runtime.

This crate offers a simple and ergonomic API to spawn asynchronous tasks, manage their lifecycle, and retrieve their results. It supports both individual task execution and efficient batch processing. Whether you need to wait for a task to complete for synchronous-style control flow, execute it in a “fire-and-forget” manner, or group multiple operations into a single batch, mini_executor provides a straightforward solution.

§Key Features

  • Simple API: A minimal surface area makes the library easy to learn and use.
  • Flexible Execution: Choose between awaiting a task’s result or running it detached.
  • Efficient Batching: Group multiple tasks into a single execution batch to reduce overhead (e.g., for database inserts or logging).
  • Built on Tokio: Leverages the power and efficiency of the tokio ecosystem.
  • Robust Error Handling: Individual task panics are captured and returned as errors, not crashed.

§Getting Started

To begin, add mini_executor, tokio, and dashmap to your Cargo.toml:

[dependencies]
tokio = { version = "1", features = ["full"] }
mini_executor = "2.0" // Replace with the desired version
dashmap = "5.5"

§Quick Start

Here’s a quick example demonstrating both individual and batch task execution.

use mini_executor::{TaskExecutor, Task, BatchTask};
use tokio::runtime::Runtime;
use std::sync::OnceLock;
use tokio::time::{sleep, Duration};

// -- Define an individual task --
struct GreetTask(String);

impl Task for GreetTask {
    type Output = String;
    async fn run(self) -> Self::Output {
        format!("Hello, {}!", self.0)
    }
}

// -- Define a batchable task --
#[derive(Clone)]
struct LogTask(String);

impl BatchTask for LogTask {
    async fn batch_run(list: Vec<Self>) {
        println!("--- Batch Log ({} tasks) ---", list.len());
        for task in list {
            println!("Logged: {}", task.0);
        }
    }
}

// -- Setup and Execution --
static RT: OnceLock<Runtime> = OnceLock::new();

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let rt = RT.get_or_init(|| Runtime::new().unwrap());
    let executor = TaskExecutor::new(rt);

    rt.block_on(async {
        // 1. Execute an individual task and wait for its result.
        let greeting = executor.execute_waiting(GreetTask("World".into())).await?;
        println!("{}", greeting); // Prints: "Hello, World!"

        // 2. Execute several batch tasks without waiting.
        executor.execute_batch_detached(LogTask("User session started".into()));
        executor.execute_batch_detached(LogTask("Data loaded".into()));
         
        // Allow a moment for the detached batch to be processed.
        sleep(Duration::from_millis(10)).await;

        // The async block must return a Result because `?` was used.
        Ok::<(), Box<dyn std::error::Error>>(())
    })?;

    Ok(())
}

Structs§

TaskExecutor
A TaskExecutor provides a simple interface for spawning tasks onto a Tokio Runtime.

Traits§

BatchTask
Represents a task that can be processed in a batch.
Task
A trait defining an asynchronously executable unit of work.