Skip to main content

backyard_core/
options.rs

1use chrono::{DateTime, Duration, Utc};
2use std::time;
3
4#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
5pub struct JobOptions {
6    pub queue: String,
7    pub delay: Option<time::Duration>,
8    pub at: Option<DateTime<Utc>>,
9    pub max_retries: u32,
10    pub priority: i32,
11}
12
13impl Default for JobOptions {
14    fn default() -> Self {
15        Self {
16            queue: "default".into(),
17            delay: None,
18            at: None,
19            max_retries: 3,
20            priority: 0,
21        }
22    }
23}
24
25impl JobOptions {
26    pub fn queue(mut self, q: impl Into<String>) -> Self {
27        self.queue = q.into();
28        self
29    }
30
31    pub fn delay(mut self, d: time::Duration) -> Self {
32        self.delay = Some(d);
33        self
34    }
35
36    pub fn at(mut self, t: DateTime<Utc>) -> Self {
37        self.at = Some(t);
38        self
39    }
40
41    pub fn max_retries(mut self, n: u32) -> Self {
42        self.max_retries = n;
43        self
44    }
45
46    pub fn priority(mut self, p: i32) -> Self {
47        self.priority = p;
48        self
49    }
50
51    pub fn scheduled_at(&self) -> DateTime<Utc> {
52        if let Some(at) = self.at {
53            return at;
54        }
55        if let Some(delay) = self.delay {
56            return Utc::now() + Duration::from_std(delay).unwrap_or_default();
57        }
58        Utc::now()
59    }
60}