Sprinter 👟
A Rust library for running parallel queued tasks
Features
- 🔄 Queue tasks and run them in parallel according to concurrency limits
- âš¡ Extremely low execution overhead
Installation
Or add to your Cargo.toml
:
[]
= "0.2.0"
Usage
Basic Example
Here's a basic example of using Sprinter to run parallel tasks:
use Queue;
use Error;
use sleep;
async
It will print:
sprint start ...
task1 start ...
task2 start ...
task2 done!
task3 start ...
task3 done!
task1 done!
sprint done in 251.949651ms
results: {"task1": Ok(Ok(1)), "task2": Ok(Ok(2)), "task3": Ok(Ok(3))}
This will execute tasks in parallel with a maximum concurrency of 2, meaning two tasks can run simultaneously. The output will show tasks running and completing based on their duration and the concurrency limit.
API
Creating a Queue
let queue: = new;
The Queue type takes two type parameters:
T
: The type of successful task resultE
: The type of error that tasks may return
Parameters:
concurrency
: Maximum number of tasks that can run in parallel
Methods
push
async
Pushes a new task to the queue. The task will be executed as soon as it is pushed or when the queue has available capacity.
Parameters:
task_id
: Unique identifier for the task. Must not be empty.task
: The task to execute. Must be a future that returnsResult<T, E>
.
Returns:
Ok(true)
if the task was successfully pushedOk(false)
if a task with the same ID already exists (deduplication)Err(QueueError)
if the task_id is empty or other errors occur
set_push_done
async
Signals that all tasks have been pushed to the queue. This must be called even if all tasks have completed, as the queue will not finish processing until this is called.
wait_for_task_done
async
Waits for a specific task to complete and returns its result.
Parameters:
task_id
: The unique identifier of the task to wait for
Returns:
Ok(Ok(T))
if the task completed successfullyOk(Err(E))
if the task failedErr(QueueError::TaskNotFound)
if the task doesn't exist
wait_for_tasks_done
async
Waits for all tasks to complete. This is the most efficient way to wait for completion when you don't need the results.
Note: set_push_done()
must be called before this method.
wait_for_results
async
Waits for all tasks to complete and returns a map of task IDs to their results.
Note: set_push_done()
must be called before this method.
Returns:
- A HashMap where:
- Keys are task IDs
- Values are the results of each task, wrapped in Result types for both task and queue errors
state
async
Returns the current state of the queue. Possible states are:
QueueState::Idle
: Queue is not processing tasksQueueState::Running
: Queue is actively processing tasksQueueState::Done
: All tasks have completed
reset
async
Resets the queue to its initial state
License
This project is licensed under the MIT License - see the LICENSE file for details.