#batch #batching #operations #series #atomically #io #atomic

atomic-batcher

一个简单的批量函数,允许您原子性地批量处理一系列操作

2 个版本

使用旧的 Rust 2015

0.8.2 2018年10月30日
0.8.0 2018年10月30日

#13 in #batching

MIT/Apache

16KB
56 代码行(不包括注释)

atomic-batcher

crates.io version build status downloads

atomic-batcher 是一个简单的批量函数,允许您原子性地批量处理一系列操作。改编自 mafintosh/atomic-batcher

  • 文档
  • Crates.io

安装

cargo add atomic-batcher

安装 cargo-edit 来扩展 Cargo,允许您通过修改 Cargo.toml 文件从命令行添加、删除和升级依赖项。

用法

extern crate atomic_batcher;
extern crate tokio;

use atomic_batcher::*;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::prelude::*;
use tokio::timer::Delay;

fn main() {
  let when = Instant::now() + Duration::from_millis(2000);
  let run = move |val: Vec<u64>, _batcher: Batcher<u64>| -> () {
    println!("{:?}", val);  
  };
  
  // Create a batcher with a run function which will be called  
  // when batcher's inner state `running` is OFF and inner state `pending_batch`
  // is not empty.
  let batcher = Batcher::new(Arc::new(run));

  // Before this first append, batcher's inner state `running` is initial OFF, 
  // so batcher will call the run function with the append value directly,
  // then inner state `running` is ON.  
  batcher.append(vec![1, 2, 3], None);

  // Now because inner state `running` is ON, run function won't be called.
  // But the data `vec![4, 5, 6]` and `vec![7, 8, 9]` will be pushed to 
  // batcher's `pending_batch`.  
  batcher.append(vec![4, 5, 6], None);
  batcher.append(vec![7, 8, 9], None);

  // Now `pending_batch` is vec![4, 5, 6, 7, 8, 9].
  // After 2 seconds, batcher.done get called which will turn `running` to OFF,
  // then call run function with `pending_batch`.
  // Finally turn `running` to ON again.  
  let task = Delay::new(when)
  .and_then(|_| {
    batcher.done(Ok(()));
    Ok(())
  })
  .map_err(|e| panic!("delay errored; err={:?}", e));
  tokio::run(task);
}

运行上述示例将打印

[1, 2, 3]

// two seconds later
[4, 5, 6, 7, 8, 9]

许可

AGPL-3.0+ 许可。见 LICENSE

依赖

~3MB
~45K SLoC