16 releases (6 breaking)

0.7.0 Jan 19, 2022
0.6.1 Oct 28, 2021
0.5.1 Oct 15, 2021
0.4.1 Oct 15, 2021
0.1.2 Nov 12, 2019

#320 in Asynchronous

Download history 8921/week @ 2023-11-20 10265/week @ 2023-11-27 9240/week @ 2023-12-04 8880/week @ 2023-12-11 9971/week @ 2023-12-18 4852/week @ 2023-12-25 8068/week @ 2024-01-01 9124/week @ 2024-01-08 9811/week @ 2024-01-15 13404/week @ 2024-01-22 14790/week @ 2024-01-29 16564/week @ 2024-02-05 16468/week @ 2024-02-12 12718/week @ 2024-02-19 15209/week @ 2024-02-26 17057/week @ 2024-03-04

62,035 downloads per month
Used in 39 crates (6 directly)

MIT/Apache

24KB
386 lines

stop-token

Cooperative cancellation for async Rust

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);
    }
}

Dependencies

~0.4–13MB
~130K SLoC