Skip to main content

spawn_with_token

Function spawn_with_token 

Source
pub fn spawn_with_token<F, T>(
    token: CancellationToken,
    future: F,
) -> JoinHandle<T>
where F: Future<Output = T> + Send + 'static, T: Send + 'static,
Expand description

spawn 一个异步任务并注入 CancellationToken

对齐 Swoole\Coroutine::create(),额外提供关闭信号监听。

§参数

  • token:关闭令牌,任务通过 token.cancelled().await 监听关闭
  • future:异步任务 future

§返回

JoinHandle<T>,调用方可 await 获取结果

§用法

use sz_rust_core::runtime::spawn_with_token;
use tokio_util::sync::CancellationToken;

let token = CancellationToken::new();
let handle = spawn_with_token(token.clone(), async move {
    // 任务执行
    42
});