Created
December 16, 2019 19:20
-
-
Save mgostIH/5bb82b84c5113caf5e717f81eb0fced4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use tokio::io::{self, AsyncWriteExt}; | |
use tokio::runtime::Runtime; | |
use tokio::fs; | |
use tokio::signal::ctrl_c; | |
use tokio::time::delay_for; | |
use chrono::{DateTime, Local}; | |
use futures::select; | |
use std::time::Duration; | |
use futures::future::FutureExt; | |
fn main() { | |
let mut rt = Runtime::new().unwrap(); | |
rt.block_on(async{ | |
timer_loop(Duration::from_secs(30), Duration::from_secs(10)).await.unwrap() | |
}) | |
} | |
async fn timer_loop(work_pause : Duration, break_pause : Duration) -> io::Result<()>{ | |
let mut current_file_task = None; | |
loop{ | |
let mut time = Local::now(); | |
println!("Starting to work!"); | |
let was_interrupted = select!{ | |
_ = delay_for(work_pause).fuse() => false, | |
x = ctrl_c().fuse() => {x?; true}, | |
}; | |
match current_file_task{ | |
Some(x) => x.await??, | |
None => (), | |
} | |
if was_interrupted{ | |
println!("Timer was stopped when we were working"); | |
write_to_file(time, Local::now()).await?; | |
break; | |
} | |
current_file_task = Some(tokio::spawn(write_to_file(time, Local::now()))); | |
time = Local::now(); | |
println!("Starting the pause!"); | |
let was_interrupted = select!{ | |
_ = delay_for(break_pause).fuse() => false, | |
x = ctrl_c().fuse() => {x?; true}, | |
}; | |
match current_file_task{ | |
Some(x) => x.await??, | |
None => (), | |
} | |
if was_interrupted{ | |
println!("Timer was stopped during the pause"); | |
write_to_file(time, Local::now()).await?; | |
break; | |
} | |
current_file_task = Some(tokio::spawn(write_to_file(time, Local::now()))); | |
} | |
Ok(()) | |
} | |
async fn write_to_file(start : DateTime<Local>, end : DateTime<Local>) -> io::Result<()>{ | |
let mut file = fs::OpenOptions::new() | |
.create(true) | |
.append(true) | |
.open("pom.txt").await?; | |
let data = format!("{} -- {}\n", start.format("%H:%M:%S"), end.format("%H:%M:%S, %a %Y-%m-%d")); | |
file.write_all(data.as_bytes()).await?; | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment