Skip to main content

apalis_cron/
tick.rs

1use std::{
2    marker::PhantomData,
3    time::{Duration, SystemTime},
4};
5
6use crate::timezone::Utc;
7
8/// Represents a single tick in the cron schedule
9#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
10#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
11pub struct Tick<Tz = Utc> {
12    /// The timestamp of the tick in UTC
13    timestamp: u64,
14    _marker: PhantomData<Tz>,
15}
16
17impl<Tz> Tick<Tz> {
18    /// Create a new context provided a timestamp
19    pub fn new(timestamp: u64) -> Self {
20        Self {
21            timestamp,
22            _marker: PhantomData,
23        }
24    }
25
26    /// Get the inner timestamp
27    pub fn get_timestamp(&self) -> u64 {
28        self.timestamp
29    }
30
31    /// Returns the duration between this tick and a [`SystemTime`].
32    ///
33    /// The `Ok` value is returned when the tick is at or after `system_time`,
34    /// while the `Err` value is returned when the tick is before `system_time`.
35    pub(crate) fn signed_duration_since(&self, time: SystemTime) -> Result<Duration, Duration> {
36        self.system_time()
37            .duration_since(time)
38            .map_err(|e| e.duration())
39    }
40
41    pub(crate) fn system_time(&self) -> SystemTime {
42        SystemTime::UNIX_EPOCH + Duration::from_secs(self.timestamp)
43    }
44}