我试图创造一个不断寻找新工作要做的未来,然后为这些工作项目维护一组未来。我想确保我的主要未来不会长时间被阻止工作,也不会同时完成我的工作。
这是我正在尝试做的事情的粗略概述。具体isDone
不存在,而且从我从文档中可以理解的内容来看,不一定是在 Rust 中使用期货的有效方法。做这种事情的惯用方法是什么?
use std::collections::HashMap;
use tokio::runtime::Runtime;
async fn find_work() -> HashMap<i64, String> {
// Go read from the DB or something...
let mut work = HashMap::new();
work.insert(1, "test".to_string());
work.insert(2, "test".to_string());
return work;
}
async fn do_work(id: i64, value: String) -> () {
// Result<(), Error> {
println!("{}: {}", id, value);
}
async fn async_main() -> () {
let mut pending_work = HashMap::new();
loop {
for (id, value) in find_work().await {
if !pending_work.contains_key(&id) {
let fut = do_work(id, value);
pending_work.insert(id, fut);
}
}
pending_work.retain(|id, fut| {
if isDone(fut) {
// do something with the result
false
} else {
true
}
});
}
}
fn main() {
let runtime = Runtime::new().unwrap();
let exec = runtime.executor();
exec.spawn(async_main());
runtime.shutdown_on_idle();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
809 次 |
最近记录: |