exit on shutdown signal

This commit is contained in:
2024-05-26 12:47:28 +02:00
parent 9b509d47ac
commit f2acf36b77
+34 -4
View File
@@ -5,6 +5,7 @@ use log::error;
use serenity::http::Http; use serenity::http::Http;
use std::env; use std::env;
use std::time::Duration; use std::time::Duration;
use tokio::io;
fn env_var(name: &str) -> anyhow::Result<String> { fn env_var(name: &str) -> anyhow::Result<String> {
env::var(name).with_context(|| format!("Unable to fetch environment variable {name}")) env::var(name).with_context(|| format!("Unable to fetch environment variable {name}"))
@@ -51,10 +52,17 @@ async fn main() -> anyhow::Result<()> {
loop { loop {
let now = chrono::Utc::now().timestamp(); let now = chrono::Utc::now().timestamp();
let sleep_secs = (now / 300 + 1) * 300 - now; let sleep_secs = (now / 300 + 1) * 300 - now;
tokio::time::sleep(Duration::from_secs( let shutdown = tokio::select! {
sleep_secs.try_into().expect("sleep_secs is negative"), result = wait_for_shutdown_signal() => {
)) result.expect("error on waiting for shutdown signal"); true
.await; },
_ = tokio::time::sleep(
Duration::from_secs(sleep_secs.try_into().expect("sleep_secs is negative"))
) => {false},
};
if shutdown {
break Ok(());
}
if let Err(err) = disbahn_client.refresh().await { if let Err(err) = disbahn_client.refresh().await {
error!("{}", err) error!("{}", err)
} }
@@ -63,3 +71,25 @@ async fn main() -> anyhow::Result<()> {
disbahn_client.refresh().await disbahn_client.refresh().await
} }
} }
async fn wait_for_shutdown_signal() -> io::Result<()> {
let ctrl_c = tokio::signal::ctrl_c();
#[cfg(unix)]
{
use tokio::signal::unix;
let sigterm = async {
unix::signal(unix::SignalKind::terminate())?.recv().await;
Ok(())
};
tokio::select! {
result = ctrl_c => { result }
result = sigterm => { result }
}
}
#[cfg(not(unix))]
ctrl_c.await
}