#[cfg(not(feature = "controller"))]
compile_error!(
"This example requires the `controller` feature: cargo run --example pipeline --features controller"
);
use std::time::Duration;
use taskvisor::prelude::*;
fn job(name: &'static str, duration: Duration) -> TaskSpec {
let task: TaskRef = TaskFn::arc(name, move |ctx: CancellationToken| async move {
println!(" [{name}] started");
let start = tokio::time::Instant::now();
tokio::select! {
_ = tokio::time::sleep(duration) => {
println!(" [{name}] completed in {:?}", start.elapsed());
Ok(())
}
_ = ctx.cancelled() => {
println!(" [{name}] cancelled after {:?}", start.elapsed());
Err(TaskError::Canceled)
}
}
});
TaskSpec::once(task)
}
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let sup = Supervisor::builder(SupervisorConfig::default())
.with_controller(taskvisor::ControllerConfig::default())
.build();
let handle = sup.serve();
println!("=== Queue Policy ===");
println!("Submit 3 jobs with the same name — they run one-by-one.\n");
for i in 1..=3 {
let spec = job("queued-job", Duration::from_millis(400));
handle
.submit(taskvisor::ControllerSpec::queue(spec))
.await?;
println!(" submitted #{i}");
}
tokio::time::sleep(Duration::from_secs(2)).await;
println!("\n=== Replace Policy ===");
println!("Submit a long job, then replace it with a short one.\n");
let long = job("replace-job", Duration::from_secs(5));
handle
.submit(taskvisor::ControllerSpec::replace(long))
.await?;
tokio::time::sleep(Duration::from_millis(300)).await;
let short = job("replace-job", Duration::from_millis(200));
handle
.submit(taskvisor::ControllerSpec::replace(short))
.await?;
tokio::time::sleep(Duration::from_secs(1)).await;
println!("\n=== DropIfRunning Policy ===");
println!("Submit a job, then try to submit another while the first is running.\n");
let first = job("drop-job", Duration::from_millis(600));
handle
.submit(taskvisor::ControllerSpec::drop_if_running(first))
.await?;
tokio::time::sleep(Duration::from_millis(100)).await;
let second = job("drop-job", Duration::from_millis(100));
handle
.submit(taskvisor::ControllerSpec::drop_if_running(second))
.await?;
println!(" (second submission should be silently dropped)");
tokio::time::sleep(Duration::from_secs(1)).await;
println!("\nDone.");
handle.shutdown().await?;
Ok(())
}