Skip to content

Commit

Permalink
Added signalling so that the process can be stopped
Browse files Browse the repository at this point in the history
Signed-off-by: Lalit Umbarkar <[email protected]>
  • Loading branch information
MrL1605 committed Jul 25, 2020
1 parent 874b0ef commit 7f4d54e
Showing 1 changed file with 75 additions and 4 deletions.
79 changes: 75 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,44 @@
use std::env::args;
use std::fs::File;
use std::io::{Read, Write};
use std::process;
use std::thread::sleep;

use chrono::{Local, Timelike};
use cron_tab::Cron;
use notify_rust::Notification;

const PID_FILE_NAME: &str = ".mahnung-pid";

fn main() {
println!("Started a cronjob at 0sec *min *hour *day *month *dayOfWeek *year");
let all_args: Vec<String> = args().collect();
let stop_command = String::from("stop");

match all_args.get(1) {
None => {
start_cron();
write_pid_to_file();

// Run an infinite loop so that only killing the server would be an option
loop {
sleep(std::time::Duration::from_secs(10));
if check_to_stop() {
break;
}
}
}
Some(cmd) => {
if cmd.eq(&stop_command) {
write_stop_to_file();
} else {
println!("This commands are not supported: {}", cmd);
}
}
}
}

fn start_cron() {
println!("Started a cronjob at 0sec *min *hour *day *month *dayOfWeek *year");
// Get current timezone and create a cron, with that timezone
let local_tz = Local::now().timezone();
let mut minutely_cron = Cron::new(local_tz);
Expand All @@ -16,10 +48,49 @@ fn main() {
.unwrap();

minutely_cron.start();
}

fn write_stop_to_file() {
let file_result = File::create(PID_FILE_NAME);
match file_result {
Ok(mut f) => {
match f.write_all(b"STOP") {
Ok(_) => println!("Stop command sent, successfully"),
Err(_) => println!("Could not send stop command"),
}
}
Err(_) => println!("Could not write PID into file.")
}
}

fn check_to_stop() -> bool {
let file_result = File::open(PID_FILE_NAME);
match file_result {
Ok(mut f) => {
let mut content = String::new();
match f.read_to_string(&mut content) {
Ok(_) => content.eq(&String::from("STOP")),
Err(_) => false
}
}
Err(_) => false
}
}

fn write_pid_to_file() {
let current_process_id = process::id();

// Run an infinite loop so that only killing the
loop {
sleep(std::time::Duration::from_secs(10));
println!("Got current process ID as {}\nWriting it in .mahnung-pid", current_process_id);
let file_result = File::create(".mahnung-pid");
match file_result {
Ok(mut f) => {
match f.write_all(format!("{}", current_process_id).as_bytes()) {
Ok(_) => (),
Err(_) => println!("Could not write PID into file. Stop command will not work")
}
()
}
Err(_) => println!("Could not write PID into file.")
}
}

Expand Down

0 comments on commit 7f4d54e

Please sign in to comment.