jobs/src/bin/using-crate-delay_timer-internal.rs
2025-02-22 23:12:53 +01:00

45 lines
1.3 KiB
Rust

use anyhow::Result;
use delay_timer::prelude::*;
use smol::Timer;
use std::time::Duration;
fn main() -> Result<()> {
// Build an DelayTimer that uses the default configuration of the `smol` runtime internally.
let delay_timer = DelayTimerBuilder::default().build();
// Develop a print job that runs in an asynchronous cycle.
// A chain of task instances.
let task_instance_chain = delay_timer.insert_task(build_task_async_print()?)?;
// Get the running instance of task 1.
let task_instance = task_instance_chain.next_with_wait()?;
// Cancel running task instances.
task_instance.cancel_with_wait()?;
// Remove task which id is 1.
delay_timer.remove_task(1)?;
// No new tasks are accepted; running tasks are not affected.
delay_timer.stop_delay_timer()?;
Ok(())
}
fn build_task_async_print() -> Result<Task, TaskError> {
let mut task_builder = TaskBuilder::default();
let body = || async {
println!("create_async_fn_body!");
Timer::after(Duration::from_secs(3)).await;
println!("create_async_fn_body:i'success");
};
task_builder
.set_task_id(1)
.set_frequency_repeated_by_seconds(1)
.set_maximum_parallel_runnable_num(2)
.spawn_async_routine(body)
}