ch-rds 0.1.5

Runtime resource loading and local service orchestration
Documentation
use std::future::Future;
use std::time::Duration;

use tokio::task::JoinHandle;
use tokio::time::MissedTickBehavior;

/// Spawns a Tokio task that executes the provided async job on a fixed interval.
pub(super) fn spawn_interval_task<F, Fut>(
    interval: Duration,
    run_on_start: bool,
    task: F,
) -> JoinHandle<()>
where
    F: Fn() -> Fut + Send + Sync + 'static,
    Fut: Future<Output = ()> + Send + 'static,
{
    tokio::spawn(async move {
        let mut ticker = tokio::time::interval(interval);
        ticker.set_missed_tick_behavior(MissedTickBehavior::Delay);

        if run_on_start {
            task().await;
        }

        // Consume the initial immediate tick so the next run aligns with the interval.
        ticker.tick().await;

        loop {
            ticker.tick().await;
            task().await;
        }
    })
}