1 // Scheduler, and trait for .seconds(), .minutes(), etc.
2 use clokwerk::{Scheduler, TimeUnits};
3 // Import week days and WeekDay
4 use diesel::{sql_query, PgConnection, RunQueryDsl};
5 use lemmy_db_schema::{source::activity::Activity, DbPool};
7 use std::{thread, time::Duration};
9 /// Schedules various cleanup tasks for lemmy in a background thread
10 pub fn setup(pool: DbPool) {
11 let mut scheduler = Scheduler::new();
13 let conn = pool.get().unwrap();
16 // On startup, reindex the tables non-concurrently
17 // TODO remove this for now, since it slows down startup a lot on lemmy.ml
18 reindex_aggregates_tables(&conn, true);
19 scheduler.every(1.hour()).run(move || {
21 reindex_aggregates_tables(&conn, true);
24 let conn = pool.get().unwrap();
25 clear_old_activities(&conn);
26 scheduler.every(1.weeks()).run(move || {
27 clear_old_activities(&conn);
30 // Manually run the scheduler in an event loop
32 scheduler.run_pending();
33 thread::sleep(Duration::from_millis(1000));
37 /// Reindex the aggregates tables every one hour
38 /// This is necessary because hot_rank is actually a mutable function:
39 /// https://dba.stackexchange.com/questions/284052/how-to-create-an-index-based-on-a-time-based-function-in-postgres?noredirect=1#comment555727_284052
40 fn reindex_aggregates_tables(conn: &PgConnection, concurrently: bool) {
44 "community_aggregates",
46 reindex_table(conn, table_name, concurrently);
50 fn reindex_table(conn: &PgConnection, table_name: &str, concurrently: bool) {
51 let concurrently_str = if concurrently { "concurrently" } else { "" };
52 info!("Reindexing table {} {} ...", concurrently_str, table_name);
53 let query = format!("reindex table {} {}", concurrently_str, table_name);
54 sql_query(query).execute(conn).expect("reindex table");
58 /// Clear old activities (this table gets very large)
59 fn clear_old_activities(conn: &PgConnection) {
60 info!("Clearing old activities...");
61 Activity::delete_olds(conn).expect("clear old activities");
65 /// Re-calculate the site and community active counts every 12 hours
66 fn active_counts(conn: &PgConnection) {
67 info!("Updating active site and community aggregates ...");
73 ("6 months", "half_year"),
77 let update_site_stmt = format!(
78 "update site_aggregates set users_active_{} = (select * from site_aggregates_activity('{}'))",
81 sql_query(update_site_stmt)
83 .expect("update site stats");
85 let update_community_stmt = format!("update community_aggregates ca set users_active_{} = mv.count_ from community_aggregates_activity('{}') mv where ca.community_id = mv.community_id_", i.1, i.0);
86 sql_query(update_community_stmt)
88 .expect("update community stats");