【发布时间】:2021-06-13 17:25:05
【问题描述】:
我正在尝试让clokwerk 安排一个异步函数每 X 秒运行一次。
The docs 显示这个例子:
// Create a new scheduler
let mut scheduler = AsyncScheduler::new();
// Add some tasks to it
scheduler
.every(10.minutes())
.plus(30.seconds())
.run(|| async { println!("Simplest is just using an async block"); });
// Spawn a task to run it forever
tokio::spawn(async move {
loop {
scheduler.run_pending().await;
tokio::time::sleep(Duration::from_millis(100)).await;
}
});
我最初的尝试:
let config2 = // define a Config struct, Config
let pg_pool2 = // get a sqlx connection pool, Pool<Postgres>
//I assume I need shared references so I use Arc
let pg_pool2 = Arc::new(pg_pool2);
let config2 = Arc::new(config2);
let mut scheduler = AsyncScheduler::new();
scheduler.every(5.seconds()).run(|| async {
println!("working!");
pull_from_main(pg_pool2.clone(), config2.clone()).await;
});
tokio::spawn(async move {
loop {
scheduler.run_pending().await;
tokio::time::sleep(Duration::from_millis(100)).await;
}
});
编译器抱怨pg_pool2 和config2 可能比借用的值更长,并建议添加move。公平的。让我们试试吧。
我的第二次尝试:
//rest the same
scheduler.every(5.seconds()).run(move || async {
//rest the same
这一次我得到了一个我自己无法破译的错误:
error: captured variable cannot escape `FnMut` closure body
--> src/main.rs:80:46
|
75 | let pg_pool2 = Arc::new(pg_pool2);
| -------- variable defined here
...
80 | scheduler.every(5.seconds()).run(move || async {
| ____________________________________________-_^
| | |
| | inferred to be a `FnMut` closure
81 | | println!("working!");
82 | | pull_from_main(pg_pool2.clone(), config2.clone()).await;
| | -------- variable captured here
83 | | });
| |_____^ returns an `async` block that contains a reference to a captured variable, which then escapes the closure body
|
= note: `FnMut` closures only have access to their captured variables while they are executing...
= note: ...therefore, they cannot allow references to captured variables to escape
有人可以帮我了解问题所在以及如何解决吗?
注意:我之前看到过这个问题,但我很难将答案应用到我的案例中。
我也是初学者,所以也许他们确实申请了,但我没有看到联系:)
【问题讨论】:
-
HS:“我也是一个初学者” tokio 和 async 世界一般不建议 rust 初学者。