stop-token

Crates.iostop-token
lib.rsstop-token
version0.7.0
sourcesrc
created_at2019-11-03 10:13:42.016026
updated_at2022-01-19 22:25:20.302589
descriptionExperimental cooperative cancellation for async Rust
homepagehttps://docs.rs/stop-token
repositoryhttps://github.com/async-rs/stop-token
max_upload_size
id177722
size26,663
Yosh (yoshuawuyts)

documentation

https://docs.rs/stop-token

README

stop-token

Cooperative cancellation for async Rust

Crates.io version Download docs.rs docs

API Docs | Releases | Contributing

See crate docs for details

You can use this crate to create a deadline received through a StopToken:

use async_std::prelude::*;
use async_std::{stream, task};

use stop_token::prelude::*;
use stop_token::StopSource;

use std::time::Duration;

#[async_std::main]
async fn main() {
    // Create a stop source and generate a token.
    let src = StopSource::new();
    let deadline = src.token();

    // When stop source is dropped, the loop will stop.
    // Move the source to a task, and drop it after 100 millis.
    task::spawn(async move {
        task::sleep(Duration::from_millis(100)).await;
        drop(src);
    });

    // Create a stream that generates numbers until
    // it receives a signal it needs to stop.
    let mut work = stream::repeat(12u8).timeout_at(deadline);

    // Loop over each item in the stream.
    while let Some(Ok(ev)) = work.next().await {
        println!("{}", ev);
    }
}

Or Instant to create a time-based deadline:

use async_std::prelude::*;
use async_std::stream;

use stop_token::prelude::*;

use std::time::{Instant, Duration};

#[async_std::main]
async fn main() {
    // Create a stream that generates numbers for 100 millis.
    let deadline = Instant::now() + Duration::from_millis(100);
    let mut work = stream::repeat(12u8).timeout_at(deadline);

    // Loop over each item in the stream.
    while let Some(Ok(ev)) = work.next().await {
        println!("{}", ev);
    }
}
Commit count: 45

cargo fmt