我是生锈的新手,我想生成一个可以在运行时中止的任务,但我很难弄清楚如何实现我想要的。
我所尝试的(不编译):
use std::time::Duration;
use axum::extract::State;
use tokio::time::sleep;
use axum::{
routing::get,
Router,
};
use tokio::task::JoinHandle;
#[derive(Clone)]
struct AppState {
join_handle: Option<JoinHandle<()>>,
}
#[tokio::main]
async fn main() {
let state = AppState { join_handle: None };
let app = Router::new()
.route("/spawn_task", get(spawn_task))
.route("/abort_task", get(abort_task))
.with_state(state);
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
}
pub async fn spawn_task(State(mut state): State<AppState>) {
state.join_handle = Some(tokio::spawn(async move {
println!("spawn task");
sleep(Duration::from_millis(10000)).await;
println!("spawn task after 10s");
}));
}
pub async fn abort_task(State(state): State<AppState>) {
state.join_handle.unwrap().abort();
}
我让它与Arc和Mutex一起工作。
use std::sync::Arc;
use std::time::Duration;
use axum::extract::State;
use tokio::time::sleep;
use axum::{
routing::get,
Router,
};
use tokio::sync::Mutex;
use tokio::task::JoinHandle;
#[derive(Clone)]
pub struct AppState {
join_handle: Arc<Mutex<Option<JoinHandle<()>>>>,
}
#[tokio::main]
async fn main() {
let state = AppState { join_handle: Arc::new(Mutex::new(None)) };
let app = Router::new()
.route("/spawn_task", get(spawn_task))
.route("/abort_task", get(abort_task))
.with_state(state);
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
}
pub async fn spawn_task(State(state): State<AppState>) {
let mut lock = state.join_handle.lock().await;
*lock = Some(tokio::spawn(async move {
println!("spawn task");
sleep(Duration::from_millis(10000)).await;
println!("spawn task after 10s");
}));
}
pub async fn abort_task(State(state): State<AppState>) {
state.join_handle.as_ref().lock().await.as_ref().unwrap().abort();
}