How can we add a shutdown hook from main for coroutines?
fun poll() = arrayOf(1,2,3,4,5,6,7,8,9)
val job = scope.launch {
while (isActive) {
val records = poll()
records.forEach {
Thread.sleep(500)
print("$it, ")
}
println("job completed")
}
}
GlobalScope.launch {
Runtime.getRuntime().addShutdownHook(object : Thread() {
override fun run() {
println("Gracefully shutting down")
job.cancelAndJoin() // cannot call this here
println("Gracefully shut!!!")
delay(20000)
}
})
}
cancelAndJoin
cannot be called in a shutdown hook because it’s a suspending function. What I’m trying to do is: when shutting down, cancel the job and wait for it to complete before terminating the JVM. How can we do that with coroutines?