use std::{
thread,
time::Duration,
};
use qubit_function::Callable;
use crate::{
TaskCompletionPair,
TaskHandle,
TaskRunner,
};
use super::Executor;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DelayExecutor {
delay: Duration,
}
impl DelayExecutor {
#[inline]
pub const fn new(delay: Duration) -> Self {
Self { delay }
}
#[inline]
pub const fn delay(&self) -> Duration {
self.delay
}
}
impl Executor for DelayExecutor {
type Execution<R, E>
= TaskHandle<R, E>
where
R: Send + 'static,
E: std::fmt::Display + Send + 'static;
fn call<C, R, E>(&self, task: C) -> Self::Execution<R, E>
where
C: Callable<R, E> + Send + 'static,
R: Send + 'static,
E: std::fmt::Display + Send + 'static,
{
let (handle, completion) = TaskCompletionPair::new().into_parts();
let delay = self.delay;
thread::spawn(move || {
if !delay.is_zero() {
thread::sleep(delay);
}
TaskRunner::new(task).run(completion);
});
handle
}
}