0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Kotlinで書いたSpringBootのバッチを異常終了させたい

Posted at

はじめに

Kotlinで、となると絶妙に情報が少ないので書いてみました。

前提

  • spring-boot-starter 2.4.x
  • Kotlin 1.4.x
SampleRunner.kt(ベースとなる起動クラス)
import org.springframework.boot.ApplicationArguments
import org.springframework.boot.ApplicationRunner
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.stereotype.Component

@Component
@ConditionalOnProperty(value = ["exec"], havingValue = "sample")
class SampleRunner : ApplicationRunner {
    override fun run(args: ApplicationArguments?) {
        // 何かしらの処理をする
    }
}

正常終了(万事うまくいったケース)

そのまま終了したら終了コード 0(正常)です。

異常終了(もう続行不能なので処理中断するケース1)

処理ロジック中でお好みのExceptionをThrowして異常終了させれば終了コード 1(異常終了)です。
ログにExceptionのStackTraceが出るので、どこでエラーが出たか分かります。

異常終了(もう続行不能なので処理中断するケース2)

終了コードのバリエーションが1だけじゃ足りない!という場合は、
特定の終了コードを返してくれるExceptionを自作しましょう。
(例:データの処理エラーは1で出社対応するけど、外部アクセスエラーでリトライしたい場合は2を返して、10分後にリトライしたい)

AbcException.kt
import org.springframework.boot.ExitCodeGenerator

class AbcException(message: String) : Exception(message), ExitCodeGenerator {
    override fun getExitCode(): Int {
        return 2
    }
}

こちらも、ログにExceptionのStackTraceが出るので、どこでエラーが出たか分かります。

警告終了(とりあえず全データ処理したんだけど一部失敗しちゃったケース)

SampleRunnerまで返ってきたけど、処理結果が万事OKというわけではない。。終了コードは0以外にしたい場合です。

SampleRunner.kt(上述)
class SampleRunner : ApplicationRunner {
    override fun run(args: ApplicationArguments?) {
        // 何かしらの処理をする
        val sampleStatus = "warning" // 実際は処理結果で判定してください!
        if( sampleStatus != "warning") {
            exitProcess(3)
        }
    }
}

こちらは、ログにStackTraceは出ません。なぜ異常終了したかは別途ログ出力しましょう。

おわり

夏は気づいたらすごい(遅い)時間になっていてこわいですね。

上記のRunnerはたぶん -Dexec=sample で動きます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?