pub struct TaskPool { /* private fields */ }Expand description
Bounded pool of tasks
Implementations§
Source§impl TaskPool
impl TaskPool
Sourcepub fn new(
concurrency: NonZeroUsize,
queue_size: NonZeroUsize,
) -> (Self, Receiver<()>)
pub fn new( concurrency: NonZeroUsize, queue_size: NonZeroUsize, ) -> (Self, Receiver<()>)
Create a new taskpool with a given concurrency and queue size (for backpressure).
use std::num::NonZeroUsize;
use std::time::Duration;
use taskpool::TaskPool;
#[tokio::main]
async fn main() {
let (pool, drained) = TaskPool::new(
NonZeroUsize::new(4).expect("non-zero concurrency"),
NonZeroUsize::new(64).expect("non-zero queue size"),
);
for i in 0..10 {
pool.spawn_with_timeout(
async move {
println!("job {i}");
tokio::time::sleep(Duration::from_millis(50)).await;
},
Duration::from_millis(250),
)
.await
.expect("schedule task");
}
pool.trigger_stop().await.expect("stop accepted");
drained.await.expect("pool drained");
}Sourcepub const fn concurrency(&self) -> usize
pub const fn concurrency(&self) -> usize
Get the concurrency of the pool
Sourcepub const fn queue_size(&self) -> usize
pub const fn queue_size(&self) -> usize
Get the queue size of the pool
Sourcepub async fn spawn(
&self,
cb: impl Future<Output = ()> + Send + 'static,
) -> Result<(), TaskPoolError>
pub async fn spawn( &self, cb: impl Future<Output = ()> + Send + 'static, ) -> Result<(), TaskPoolError>
Spawn a task in the pool with the default timeout.
If a task can’t be inserted, it will wait until it can.
It’s usually better to use spawn_with_timeout, to avoid locking.
§Errors
Returns an error if fails to schedule (e.g., timeout or channel closed).
Sourcepub async fn spawn_with_timeout(
&self,
cb: impl Future<Output = ()> + Send + 'static,
timeout: Duration,
) -> Result<(), TaskPoolError>
pub async fn spawn_with_timeout( &self, cb: impl Future<Output = ()> + Send + 'static, timeout: Duration, ) -> Result<(), TaskPoolError>
Spawn a task in the pool with the given timeout. Timeout is not for the task, but for channel queue insertion.
§Errors
Returns an error if fails to schedule (e.g., timeout or channel closed).
Sourcepub async fn trigger_stop(&self) -> Result<(), TaskPoolError>
pub async fn trigger_stop(&self) -> Result<(), TaskPoolError>
Trigger a stop by adding a special event in the pool. Everything after this marker will not be consumed and the consuming of the queue will be stopped.
§Errors
Returns an error if fails to schedule.