shutdown server gracefully

This commit is contained in:
hrj 2022-03-01 13:23:29 +05:30
parent 2d9fd3c68e
commit a54947cfc2
4 changed files with 43 additions and 9 deletions

View File

@ -25,6 +25,15 @@ object LCFramework {
playgroundEnabled = config.playgroundEnabled,
corsHeader = config.corsHeader
)
Runtime.getRuntime.addShutdownHook( new Thread {
override def run(): Unit = {
println("Shutting down gracefully...")
backgroundTask.shutdown()
}
}
)
server.start()
}
}

View File

@ -22,6 +22,7 @@ class BackgroundTask(config: Config, captchaManager: CaptchaManager) {
val requiredCountPerCombination = Math.max(1, (config.throttle * 1.01) / allCombinations.size).toInt
for (param <- allCombinations) {
if (!shutdownInProgress) {
val countExisting = captchaManager.getCount(param).getOrElse(0)
val countRequired = requiredCountPerCombination - countExisting
if (countRequired > 0) {
@ -29,10 +30,13 @@ class BackgroundTask(config: Config, captchaManager: CaptchaManager) {
println(s"Creating $countCreate of $countRequired captchas for $param")
for (i <- 0 until countCreate) {
if (!shutdownInProgress) {
captchaManager.generateChallenge(param)
}
}
}
}
}
} catch { case exception: Exception => println(exception) }
}
}
@ -62,9 +66,22 @@ class BackgroundTask(config: Config, captchaManager: CaptchaManager) {
list(HelperFunctions.randomNumber(list.size))
}
private val ex = new ScheduledThreadPoolExecutor(1)
def beginThread(delay: Int): Unit = {
val ex = new ScheduledThreadPoolExecutor(1)
ex.scheduleWithFixedDelay(task, 1, delay, TimeUnit.SECONDS)
}
@volatile var shutdownInProgress = false
def shutdown(): Unit = {
println(" Shutting down background task...")
shutdownInProgress = true
ex.shutdown()
println(" Finished Shutting background task")
println(" Shutting down DB...")
Statements.tlStmts.get.shutdown.execute()
println(" Finished shutting down db")
}
}

View File

@ -3,7 +3,7 @@ package lc.database
import java.sql.{Connection, DriverManager, Statement}
class DBConn() {
val con: Connection = DriverManager.getConnection("jdbc:h2:./data/H2/captcha2", "sa", "")
val con: Connection = DriverManager.getConnection("jdbc:h2:./data/H2/captcha2;MAX_COMPACT_TIME=8000;DB_CLOSE_ON_EXIT=FALSE", "sa", "")
def getStatement(): Statement = {
con.createStatement()

View File

@ -120,6 +120,14 @@ class Statements(dbConn: DBConn, maxAttempts: Int) {
"SELECT * FROM mapId"
)
val shutdown: PreparedStatement = dbConn.con.prepareStatement(
"SHUTDOWN"
)
val shutdownCompact: PreparedStatement = dbConn.con.prepareStatement(
"SHUTDOWN COMPACT"
)
}
object Statements {