background updating works

This commit is contained in:
Edward Shen 2019-05-01 13:22:23 -04:00
parent f357316797
commit af79f6d2a3
Signed by: edward
GPG key ID: F350507060ED6C90
2 changed files with 17 additions and 8 deletions

View file

@ -7,7 +7,7 @@ use actix_web::{
use reqwest::{Client, Url, UrlError};
use serde::Serialize;
use std::sync::{Arc, MutexGuard, RwLock, RwLockWriteGuard};
use std::sync::{Arc, RwLock};
use tera::{Context, Tera};
#[derive(Clone, Serialize, Default, Debug)]
@ -45,13 +45,21 @@ pub fn json_endpoint(state: Data<State>) -> HttpResponse {
HttpResponse::Ok().json(&state.statuses)
}
pub fn update_state(mut state: RwLockWriteGuard<QueryResults>) -> RwLockWriteGuard<QueryResults> {
if EpochTimestamp::now() - state.last_update >= state.refresh_time {
state.last_update = EpochTimestamp::now();
state.statuses = update_status(&state.config);
pub fn update_state(state: State) {
let mut new_timestamp = None;
let mut new_statuses = None;
{
let read_state = state.read().unwrap();
if EpochTimestamp::now() - read_state.last_update >= read_state.refresh_time {
new_timestamp = Some(EpochTimestamp::now());
new_statuses = Some(update_status(&read_state.config));
}
}
if new_timestamp.is_some() {
let mut write_state = state.try_write().expect("Could not unlock");
write_state.last_update = new_timestamp.unwrap();
write_state.statuses = new_statuses.unwrap();
}
state
}
fn update_status(config: &Config) -> Vec<Status> {

View file

@ -62,7 +62,8 @@ fn main() {
tokio::spawn(
Interval::new_interval(Duration::from_millis(5000))
.for_each(move |_| {
let _ = update_state(clone_state.write().unwrap());
let state = Arc::clone(&clone_state);
update_state(state);
Ok(())
})
.map_err(|_| ()),