From ff712809b59b7d379ad2da2e7fdc3e906c203f56 Mon Sep 17 00:00:00 2001 From: Andrea Cavalli Date: Tue, 28 Sep 2021 00:19:34 +0200 Subject: [PATCH] Add shutdown hook --- .../java/it/tdlight/client/SimpleTelegramClient.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/main/java/it/tdlight/client/SimpleTelegramClient.java b/src/main/java/it/tdlight/client/SimpleTelegramClient.java index 9d8e5a2..d2a7cfa 100644 --- a/src/main/java/it/tdlight/client/SimpleTelegramClient.java +++ b/src/main/java/it/tdlight/client/SimpleTelegramClient.java @@ -174,6 +174,18 @@ public final class SimpleTelegramClient implements Authenticable { this.authenticationData = authenticationData; createDirectories(); client.initialize(this::handleUpdate, this::handleUpdateException, this::handleDefaultException); + + // Handle unexpected shutdown + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + try { + // Send close function + this.client.send(new TdApi.Close(), ok -> {}, ex -> {}); + // Wait until the client has been closed successfully + this.waitForExit(); + } catch (Throwable ignored) { + // Ignore errors since we are shutting down everything + } + })); } private void createDirectories() {