BatchTask

Trait BatchTask 

Source
pub trait BatchTask:
    Sized
    + Send
    + 'static {
    // Required method
    fn batch_run(list: Vec<Self>) -> impl Future<Output = ()> + Send;
}
Expand description

Represents a task that can be processed in a batch.

This trait is designed for operations that can be optimized by grouping them together, such as database inserts, logging, or sending notifications. When multiple tasks of the same type are submitted to the TaskExecutor in quick succession, they are collected and executed in a single call to batch_run. Note that the batch_run function does not return a value and its signature must resolve to ().

§Type Constraints

  • Sized + Send + 'static: Ensures the task can be owned and moved between threads.

§Example

use mini_executor::{TaskExecutor, BatchTask};
use tokio::runtime::{Runtime, Builder};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, OnceLock};

// 1. Define a task that holds a reference to a shared counter.
#[derive(Clone)]
struct IncrementTask(Arc<AtomicUsize>);

// 2. Implement BatchTask to process multiple increments at once.
impl BatchTask for IncrementTask {
    async fn batch_run(list: Vec<Self>) {
        if list.is_empty() { return; }
        // Access the Arc from the *first task* in the vector.
        let counter = list[0].0.clone();
        let total_increments = list.len();
        println!("Batch processing {} increments.", total_increments);
        counter.fetch_add(total_increments, Ordering::SeqCst);
    }
}

// 3. Execute the batch task using a TaskExecutor.
static RT: OnceLock<Runtime> = OnceLock::new();

fn main() {
    let rt = RT.get_or_init(|| Builder::new_current_thread().build().unwrap());
    let executor = TaskExecutor::new(rt);
    let counter = Arc::new(AtomicUsize::new(0));

    rt.block_on(async {
        // We can execute and wait for a batch.
        executor.execute_batch_waiting(IncrementTask(counter.clone())).await.unwrap();
        assert_eq!(counter.load(Ordering::SeqCst), 1);

        // Or execute several in a fire-and-forget manner.
        executor.execute_batch_detached(IncrementTask(counter.clone()));
        executor.execute_batch_detached(IncrementTask(counter.clone()));

        // Await the final task to ensure the previous detached ones are also processed.
        executor.execute_batch_waiting(IncrementTask(counter.clone())).await.unwrap();
    });
     
    assert_eq!(counter.load(Ordering::SeqCst), 4);
    println!("Final counter value: {}", counter.load(Ordering::SeqCst));
}

Required Methods§

Source

fn batch_run(list: Vec<Self>) -> impl Future<Output = ()> + Send

The core logic for processing a batch of tasks.

This method receives a Vec<Self> containing all tasks collected for the batch. It should perform the work and return a Future that resolves when the batch is complete.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§