apalis_core/backend/poll_strategy/strategies/
interval.rs

1use std::time::Duration;
2
3use futures_core::stream::BoxStream;
4use futures_util::{StreamExt, stream};
5
6use crate::backend::poll_strategy::{BackoffConfig, BackoffStrategy, PollContext, PollStrategy};
7
8/// Interval-based polling strategy with optional backoff
9#[derive(Debug, Clone)]
10pub struct IntervalStrategy {
11    pub(super) poll_interval: Duration,
12}
13
14impl IntervalStrategy {
15    /// Create a new IntervalStrategy with the specified interval
16    #[must_use]
17    pub fn new(interval: Duration) -> Self {
18        Self {
19            poll_interval: interval,
20        }
21    }
22
23    /// Wrap the IntervalStrategy with a BackoffStrategy
24    /// This will apply exponential backoff to the polling interval
25    /// based on the provided [`BackoffConfig`].`
26    #[must_use]
27    pub fn with_backoff(self, config: BackoffConfig) -> BackoffStrategy {
28        BackoffStrategy::new(self, config)
29    }
30}
31
32impl PollStrategy for IntervalStrategy {
33    type Stream = BoxStream<'static, ()>;
34
35    fn poll_strategy(self: Box<Self>, _: &PollContext) -> Self::Stream {
36        let interval = self.poll_interval;
37        stream::unfold((), move |()| {
38            let fut = futures_timer::Delay::new(interval);
39            async move {
40                fut.await;
41                Some(((), ()))
42            }
43        })
44        .boxed()
45    }
46}