0

我正在尝试构建一个机器人来检查帐户连接到每个帐户的服务的状态,我想既然他们必须做一些I/O我会尝试使用的Tokio(也“让我的骨头”,因为我从来没有用过)。
我得出了类似于以下的代码:

#[tokio::main]
async fn main() {
    // Load config file
    let config = Config::parse("config.toml").await.unwrap();

    // Get accounts data
    let accounts = config.accounts();

    // Init a bot for each account
    let mut tasks = Vec::with_capacity(accounts.len());
    for account in accounts {
        // Init bot client (wrapper for Reqwest::Client)
        let client = Client::new(account).await;
        if let Err(e) = client {
            println!("ERROR {}", e);
            continue;
        }

        let task = tokio::spawn(async move || {
            let client = client.unwrap();
            tokio::pin!(client);

            loop {
                // Do login
                let login = do_login(&mut client).await;
                if let Err(e) = login {
                    println!("ERROR {}", e);
                    tokio::time::sleep(60).await;
                    continue;
                }

                // Loop until X number of errors occurs
                let mut errors = 0;
                while errors < 50 {
                    // Get information
                    let info = get_info(&client).await;
                    if let Err(e) = info {
                        println!("ERROR {}", e);
                        tokio::time::sleep(120).await;
                        errors += 1;
                        continue;
                    }

                    // Send a confirmation
                    let info_id = info.unwrap();
                    let submit = do_sumbit(info_id, &client).await;
                    if let Err(e) = submit {
                        println!("ERROR {}", e);
                        tokio::time::sleep(60).await;
                        errors += 1;
                    }
                }
            }
        });
        
        tasks.push(task);
    }

    // Join all clients
    join_all(tasks).await;
}

async do_login(client: &mut Pin<&mut Client>) -> Result<(), CustomError> {
    // work async mainly with reqwest
}

async get_info(client: &Pin<&mut Client>) -> Result<String, CustomError> {
    // work async mainly with reqwest
}

async do_sumbit(info_id: String, client: &Pin<&mut Client>) -> Result<(), CustomError> {
    // work async mainly with reqwest
}
  • 这段代码实际上是异步和并发的吗?
  • 我在想,如果要管理的帐户数量比主机的 CPU 数量大得多,异步方法更好,还是我错了?
4

0 回答 0