handle signals using signal-hook

This commit is contained in:
Denis-Cosmin Nutiu 2024-12-26 19:34:56 +02:00
parent 291d84dfd0
commit f70a9041ed
3 changed files with 18 additions and 7 deletions

View file

@ -1,5 +1,4 @@
# Docker Compose file used for testing # Docker Compose file used for testing
version: '3.8'
services: services:
redis: redis:
container_name: bluesky-bot-local-redis container_name: bluesky-bot-local-redis

View file

@ -11,7 +11,7 @@ reqwest = "0.12.9"
scraper = "0.22.0" scraper = "0.22.0"
clokwerk = "0.4.0" clokwerk = "0.4.0"
log = "0.4.22" log = "0.4.22"
ctrlc = "3.4.5"
clap = { version = "4.5.23", features = ["derive"] } clap = { version = "4.5.23", features = ["derive"] }
post = {path = "../post"} post = {path = "../post"}
infrastructure = { path = "../infrastructure"} infrastructure = { path = "../infrastructure"}
signal-hook = "0.3.17"

View file

@ -6,9 +6,11 @@ use clokwerk::{AsyncScheduler, Interval, TimeUnits};
use infrastructure::RedisService; use infrastructure::RedisService;
use log::{debug, error, info}; use log::{debug, error, info};
use post::NewsPost; use post::NewsPost;
use signal_hook::{consts::SIGINT, consts::SIGTERM, iterator::Signals};
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, Sender}; use std::sync::mpsc::{Receiver, Sender};
use std::sync::{mpsc, Arc}; use std::sync::{mpsc, Arc};
use std::thread;
use std::time::Duration; use std::time::Duration;
use tokio::task::JoinHandle; use tokio::task::JoinHandle;
@ -67,10 +69,20 @@ async fn main() -> Result<(), anyhow::Error> {
// Graceful shutdown. // Graceful shutdown.
let running = Arc::new(AtomicBool::new(true)); let running = Arc::new(AtomicBool::new(true));
let r = running.clone(); let r = running.clone();
ctrlc::set_handler(move || {
r.store(false, Ordering::SeqCst); thread::spawn(move || {
}) let signals = Signals::new([SIGINT, SIGTERM]);
.expect("Error setting Ctrl-C handler"); match signals {
Ok(mut signal_info) => {
if signal_info.forever().next().is_some() {
r.store(false, Ordering::SeqCst);
}
}
Err(error) => {
error!("Failed to setup signal handler: {error}")
}
}
});
run_scrapping_job(&mut scheduler, tx, args.scrape_interval_minutes.minutes()); run_scrapping_job(&mut scheduler, tx, args.scrape_interval_minutes.minutes());