Skip to main content

TaskQueue

Struct TaskQueue 

Source
pub struct TaskQueue { /* private fields */ }
Expand description

A thread-based task queue with configurable concurrency and priority scheduling.

Workers continuously pull the highest-priority task from the queue and execute it. When the queue is shut down, running tasks are allowed to complete but pending tasks are dropped (their handles will receive TaskError::Cancelled).

§Example

use philiprehberger_task_queue::{TaskQueue, Priority};

let queue = TaskQueue::new(2);

let h1 = queue.submit(|| 10);
let h2 = queue.submit_with_priority(Priority::High, || 20);

assert_eq!(h1.join().unwrap(), 10);
assert_eq!(h2.join().unwrap(), 20);

queue.shutdown();

Implementations§

Source§

impl TaskQueue

Source

pub fn new(concurrency: usize) -> Self

Create a new task queue with the given number of worker threads.

§Panics

Panics if concurrency is zero.

Source

pub fn submit<F, T>(&self, task: F) -> TaskHandle<T>
where F: FnOnce() -> T + Send + 'static, T: Send + 'static,

Submit a task with Normal priority.

Returns a TaskHandle that can be used to retrieve the result.

Source

pub fn submit_with_priority<F, T>( &self, priority: Priority, task: F, ) -> TaskHandle<T>
where F: FnOnce() -> T + Send + 'static, T: Send + 'static,

Submit a task with the given priority.

Higher-priority tasks are executed before lower-priority ones when multiple tasks are waiting in the queue.

Returns a TaskHandle that can be used to retrieve the result.

If the queue is draining or shut down, the returned handle will immediately yield TaskError::Cancelled.

Source

pub fn stats(&self) -> TaskQueueStats

Return a snapshot of task queue statistics.

The counters are updated atomically as tasks are submitted, completed, and failed, so successive calls may return different values.

§Example
use philiprehberger_task_queue::TaskQueue;

let queue = TaskQueue::new(1);
let handle = queue.submit(|| 1 + 1);
handle.join().unwrap();

let stats = queue.stats();
assert_eq!(stats.total_submitted, 1);
assert_eq!(stats.completed, 1);
queue.shutdown();
Source

pub fn drain(self)

Stop accepting new tasks and wait for all queued and in-flight tasks to complete.

Unlike shutdown, drain does not drop pending tasks — every task that was already submitted will run to completion. New submissions made after drain is called will be immediately cancelled.

This method blocks until the queue is empty and all workers are idle, then shuts down the worker threads.

§Example
use philiprehberger_task_queue::TaskQueue;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

let queue = TaskQueue::new(2);
let counter = Arc::new(AtomicUsize::new(0));

for _ in 0..5 {
    let c = counter.clone();
    queue.submit(move || { c.fetch_add(1, Ordering::SeqCst); });
}

queue.drain();
assert_eq!(counter.load(Ordering::SeqCst), 5);
Source

pub fn on_complete<F>(&self, callback: F)
where F: Fn(bool, Duration) + Send + Sync + 'static,

Register a callback that fires after each task completes.

The callback receives two arguments:

  • successtrue if the task completed without panicking, false otherwise.
  • duration — wall-clock time the task took to execute.

Only one callback may be active at a time; calling this again replaces the previous callback.

§Example
use philiprehberger_task_queue::TaskQueue;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

let queue = TaskQueue::new(1);
let count = Arc::new(AtomicUsize::new(0));
let c = count.clone();
queue.on_complete(move |_success, _dur| {
    c.fetch_add(1, Ordering::SeqCst);
});

queue.submit(|| 42).join().unwrap();
assert_eq!(count.load(Ordering::SeqCst), 1);
queue.shutdown();
Source

pub fn shutdown(self)

Shut down the task queue.

Signals all workers to stop, waits for currently running tasks to finish, and drops any pending tasks. Pending task handles will receive TaskError::Cancelled when joined.

Trait Implementations§

Source§

impl Drop for TaskQueue

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.