Skip to main content

task_register

Function task_register 

Source
pub fn task_register(
    period: Duration,
    callback: Arc<dyn Fn() + Send + Sync>,
) -> TaskHandle
Expand description

Register a periodic task that fires its callback every period.

The first invocation occurs after period elapses. The task runs on the current tokio runtime, so this function must be called from inside one (e.g. inside #[tokio::main] or a block_on).

ยงExamples

use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;
use dynomite::core::task::task_register;

let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
    let n = Arc::new(AtomicUsize::new(0));
    let nn = n.clone();
    let handle = task_register(Duration::from_millis(2), Arc::new(move || {
        nn.fetch_add(1, Ordering::Relaxed);
    }));
    tokio::time::sleep(Duration::from_millis(15)).await;
    handle.cancel();
});