pingora_load_balancing/
background.rs1use std::time::{Duration, Instant};
18
19use super::{BackendIter, BackendSelection, LoadBalancer};
20use async_trait::async_trait;
21use pingora_core::services::background::BackgroundService;
22
23#[async_trait]
24impl<S: Send + Sync + BackendSelection + 'static> BackgroundService for LoadBalancer<S>
25where
26 S::Iter: BackendIter,
27{
28 async fn start(&self, shutdown: pingora_core::server::ShutdownWatch) -> () {
29 const NEVER: Duration = Duration::from_secs(u32::MAX as u64);
31 let mut now = Instant::now();
32 let mut next_update = now;
34 let mut next_health_check = now;
35 loop {
36 if *shutdown.borrow() {
37 return;
38 }
39
40 if next_update <= now {
41 let _ = self.update().await;
43 next_update = now + self.update_frequency.unwrap_or(NEVER);
44 }
45
46 if next_health_check <= now {
47 self.backends
48 .run_health_check(self.parallel_health_check)
49 .await;
50 next_health_check = now + self.health_check_frequency.unwrap_or(NEVER);
51 }
52
53 if self.update_frequency.is_none() && self.health_check_frequency.is_none() {
54 return;
55 }
56 let to_wake = std::cmp::min(next_update, next_health_check);
57 tokio::time::sleep_until(to_wake.into()).await;
58 now = Instant::now();
59 }
60 }
61}