@@ -15,6 +15,11 @@ extern crate serde_json;
15
15
16
16
use std:: error:: Error ;
17
17
use std:: path:: PathBuf ;
18
+ use signal_hook:: consts:: signal:: { SIGINT , SIGTERM } ;
19
+ use signal_hook:: iterator:: Signals ;
20
+ use std:: sync:: mpsc;
21
+ use std:: thread;
22
+ use std:: time:: Duration ;
18
23
19
24
use chrono:: { DateTime , Utc } ;
20
25
use clap:: { Parser , Subcommand } ;
@@ -207,16 +212,36 @@ fn main() -> Result<(), Box<dyn Error>> {
207
212
}
208
213
209
214
fn daemon ( client : & AwClient ) -> Result < ( ) , Box < dyn Error > > {
210
- loop {
215
+ let ( tx, rx) = mpsc:: channel ( ) ;
216
+
217
+ // Spawn a thread to handle signals
218
+ let mut signals = Signals :: new ( & [ SIGTERM , SIGINT ] ) ?;
219
+ thread:: spawn ( move || {
220
+ for _ in signals. forever ( ) {
221
+ let _ = tx. send ( ( ) ) ;
222
+ }
223
+ } ) ;
224
+
225
+ loop {
211
226
if let Err ( e) = daemon_sync_cycle ( client) {
212
227
error ! ( "Error during sync cycle: {}" , e) ;
213
228
// Re-throw the error
214
229
return Err ( e) ;
215
230
}
216
231
217
232
info ! ( "Sync pass done, sleeping for 5 minutes" ) ;
218
- std:: thread:: sleep ( std:: time:: Duration :: from_secs ( 300 ) ) ;
233
+
234
+ // Wait for either the sleep duration or a signal
235
+ match rx. recv_timeout ( Duration :: from_secs ( 300 ) ) {
236
+ Ok ( _) | Err ( mpsc:: RecvTimeoutError :: Disconnected ) => {
237
+ info ! ( "Received termination signal, shutting down" ) ;
238
+ break ;
239
+ }
240
+ Err ( mpsc:: RecvTimeoutError :: Timeout ) => { }
241
+ }
219
242
}
243
+
244
+ Ok ( ( ) )
220
245
}
221
246
222
247
fn daemon_sync_cycle ( client : & AwClient ) -> Result < ( ) , Box < dyn Error > > {
0 commit comments