this repo has no description
1use anyhow::Result;
2use chrono::Utc;
3use tokio_util::sync::CancellationToken;
4
5use crate::storage::{feed_content_truncate_oldest, StoragePool};
6
7pub struct CleanTask {
8 pool: StoragePool,
9 max_age: chrono::Duration,
10 cancellation_token: CancellationToken,
11}
12
13impl CleanTask {
14 pub fn new(
15 pool: StoragePool,
16 max_age: chrono::Duration,
17 cancellation_token: CancellationToken,
18 ) -> Self {
19 Self {
20 pool,
21 max_age,
22 cancellation_token,
23 }
24 }
25
26 pub async fn run_background(&self, interval: chrono::Duration) -> Result<()> {
27 let interval = interval.to_std()?;
28
29 let sleeper = tokio::time::sleep(interval);
30 tokio::pin!(sleeper);
31
32 loop {
33 tokio::select! {
34 () = self.cancellation_token.cancelled() => {
35 break;
36 },
37 () = &mut sleeper => {
38
39 if let Err(err) = self.main().await {
40 tracing::error!("CleanTask task failed: {}", err);
41 }
42
43
44 sleeper.as_mut().reset(tokio::time::Instant::now() + interval);
45 }
46 }
47 }
48 Ok(())
49 }
50
51 pub async fn main(&self) -> Result<()> {
52 let now = Utc::now();
53 let max_age = now - self.max_age;
54 feed_content_truncate_oldest(&self.pool, max_age).await
55 }
56}