Skip to content

Commit ed26535

Browse files
committed
feat(sync): gracefully handle SIGTERMs (ActivityWatch#516)
* chore(sync): add ctrlc dependency * feat(sync): gracefully handle SIGTERMs
1 parent adf8a6f commit ed26535

File tree

3 files changed

+59
-11
lines changed

3 files changed

+59
-11
lines changed

Cargo.lock

Lines changed: 35 additions & 7 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

aw-sync/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ clap = { version = "4.1", features = ["derive"] }
2323
appdirs = "0.2.0"
2424
dirs = "5.0.1"
2525
gethostname = "0.4.3"
26+
ctrlc = "3.4.5"
2627

2728
aw-server = { path = "../aw-server" }
2829
aw-models = { path = "../aw-models" }

aw-sync/src/main.rs

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,12 @@ extern crate chrono;
1313
extern crate serde;
1414
extern crate serde_json;
1515

16-
use std::error::Error;
17-
use std::path::PathBuf;
18-
1916
use chrono::{DateTime, Utc};
2017
use clap::{Parser, Subcommand};
18+
use std::error::Error;
19+
use std::path::PathBuf;
20+
use std::sync::mpsc::{channel, RecvTimeoutError};
21+
use std::time::Duration;
2122

2223
use aw_client_rust::blocking::AwClient;
2324

@@ -207,6 +208,12 @@ fn main() -> Result<(), Box<dyn Error>> {
207208
}
208209

209210
fn daemon(client: &AwClient) -> Result<(), Box<dyn Error>> {
211+
let (tx, rx) = channel();
212+
213+
ctrlc::set_handler(move || {
214+
let _ = tx.send(());
215+
})?;
216+
210217
loop {
211218
if let Err(e) = daemon_sync_cycle(client) {
212219
error!("Error during sync cycle: {}", e);
@@ -215,8 +222,20 @@ fn daemon(client: &AwClient) -> Result<(), Box<dyn Error>> {
215222
}
216223

217224
info!("Sync pass done, sleeping for 5 minutes");
218-
std::thread::sleep(std::time::Duration::from_secs(300));
225+
226+
// Wait for either the sleep duration or a termination signal
227+
match rx.recv_timeout(Duration::from_secs(300)) {
228+
Ok(_) | Err(RecvTimeoutError::Disconnected) => {
229+
info!("Termination signal received, shutting down.");
230+
break;
231+
}
232+
Err(RecvTimeoutError::Timeout) => {
233+
// Continue the loop if the timeout occurs
234+
}
235+
}
219236
}
237+
238+
Ok(())
220239
}
221240

222241
fn daemon_sync_cycle(client: &AwClient) -> Result<(), Box<dyn Error>> {

0 commit comments

Comments
 (0)