Cancel console instance and join when JVM shutdown, if initialized

This commit is contained in:
Him188 2022-02-16 08:35:51 +00:00
parent 7252879f46
commit f71ca64b0a
2 changed files with 13 additions and 11 deletions

View File

@ -43,6 +43,7 @@ import java.nio.file.Path
import java.util.*
import java.util.concurrent.locks.ReentrantLock
import kotlin.annotation.AnnotationTarget.*
import kotlin.concurrent.thread
import kotlin.coroutines.CoroutineContext
@ -356,6 +357,14 @@ public interface MiraiConsoleImplementation : CoroutineScope {
override val resolvedPlugins: MutableList<Plugin> get() = MiraiConsole.pluginManagerImpl.resolvedPlugins
}
init {
Runtime.getRuntime().addShutdownHook(thread(false) {
if (instanceInitialized) {
runBlocking { MiraiConsole.job.cancelAndJoin() }
}
})
}
@Volatile
internal var instance: MiraiConsoleImplementation? = null
internal val instanceInitialized: Boolean get() = instance != null

View File

@ -1,10 +1,10 @@
/*
* Copyright 2019-2021 Mamoe Technologies and contributors.
* Copyright 2019-2022 Mamoe Technologies and contributors.
*
* 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
* Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
* 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
* Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
*
* https://github.com/mamoe/mirai/blob/master/LICENSE
* https://github.com/mamoe/mirai/blob/dev/LICENSE
*/
package net.mamoe.mirai.console.command
@ -53,7 +53,6 @@ import java.lang.management.ManagementFactory
import java.lang.management.MemoryUsage
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import kotlin.concurrent.thread
import kotlin.math.floor
import kotlin.system.exitProcess
@ -118,12 +117,6 @@ public object BuiltInCommands {
}
}
init {
Runtime.getRuntime().addShutdownHook(thread(false) {
MiraiConsole.cancel()
})
}
public object StopCommand : SimpleCommand(
ConsoleCommandOwner, "stop", "shutdown", "exit",
description = "关闭 Mirai Console",