Skip to main content

Scope

Struct Scope 

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

A Scope for spawning Tokio Tasks.

When the Scope is dropped, any tasks which are still executing are cancelled. If you want to cancel all tasks sooner, you can use Scope::cancel().

Implementations§

Source§

impl Scope

Source

pub fn new() -> Self

Create a new scoped task spawner

Tasks may be cancelled manually, using cancel(), or automatically when the Scope is dropped.

Source

pub fn cancel(&self)

Cancel all the spawned, and still executing, tasks.

Source

pub fn spawn<F, R>(&self, future: F) -> JoinHandle<Option<F::Output>>
where F: Future<Output = R> + Send + 'static, R: Send + 'static,

Spawn a task within the scope.

This function is the primary way to introduce concurrency within a Scope. The spawned task will be cancelled automatically when the Scope is dropped or when Scope::cancel() is called.

§When to use spawn

Use spawn when you need to react to the outcome of the spawned task. It returns a JoinHandle<Option<Output>>, allowing you to .await the result. The Option will be:

  • Some(value) if the future completes successfully.
  • None if the future is cancelled before completion.

If you only need to run a side-effect on completion or cancellation (like decrementing a counter), consider using Scope::spawn_with_hooks for a more direct API.

use scope_spawn::scope::Scope;
use std::time::Duration;
use tokio::time::sleep;

#[tokio::main]
async fn main() {
    let scope = Scope::new();

    let handle = scope.spawn(async {
        // Simulate some work
        sleep(Duration::from_millis(10)).await;
        "Hello from a spawned task!"
    });

    let result = handle.await.unwrap();
    assert!(result.is_some());
    assert_eq!(result.unwrap(), "Hello from a spawned task!");

    // scope is dropped here, and any remaining tasks are cancelled.
}
Source

pub fn spawn_with_hooks<F, C, D, R>( &self, future: F, on_completion: C, on_cancellation: D, )
where F: Future<Output = R> + Send + 'static, C: FnOnce() + Send + 'static, D: FnOnce() + Send + 'static, R: Send + 'static,

Spawn a “fire-and-forget” task with completion and cancellation hooks.

This function is useful when you need to execute a side-effect based on the task’s outcome, but do not need to handle its return value directly.

  • The on_completion closure runs if the task finishes successfully.
  • The on_cancellation closure runs if the task is cancelled.
§When to use spawn_with_hooks

This method is ideal for managing resources, such as semaphores or counters, that are tied to the lifecycle of a task. For example, you might decrement an “in-flight requests” counter in both hooks to ensure it’s always accurate, regardless of how the task terminates.

If you need to await the task’s result, use Scope::spawn instead.

use scope_spawn::scope::Scope;
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;

#[tokio::main]
async fn main() {
    let scope = Scope::new();
    let completed_count = Arc::new(AtomicUsize::new(0));

    let count_clone = completed_count.clone();
    scope.spawn_with_hooks(
        async { /* ... */ },
        move || { count_clone.fetch_add(1, Ordering::SeqCst); },
        || { /* handle cancellation */ }
    );

    // Give the task time to complete.
    tokio::time::sleep(std::time::Duration::from_millis(10)).await;

    assert_eq!(completed_count.load(Ordering::SeqCst), 1);
    // scope is dropped here, and spawned tasks are cancelled.
}

Trait Implementations§

Source§

impl Clone for Scope

Source§

fn clone(&self) -> Scope

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Scope

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Scope

Source§

fn default() -> Scope

Returns the “default value” for a type. Read more
Source§

impl Drop for Scope

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

§

impl Freeze for Scope

§

impl RefUnwindSafe for Scope

§

impl Send for Scope

§

impl Sync for Scope

§

impl Unpin for Scope

§

impl UnsafeUnpin for Scope

§

impl UnwindSafe for Scope

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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.