Skip to content

Commit

Permalink
ExecutionAwareTimedJob
Browse files Browse the repository at this point in the history
  • Loading branch information
ofarukdogancay committed Jul 3, 2024
1 parent af255d9 commit adef59e
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.valensas.simplyquartz

import org.quartz.JobExecutionContext
import org.quartz.PersistJobDataAfterExecution
import org.slf4j.LoggerFactory
import java.time.Instant
import java.util.*

@PersistJobDataAfterExecution
abstract class ExecutionAwareTimedJob : TimedJob() {


private val logger = LoggerFactory.getLogger(javaClass)

override fun executeTimed(context: JobExecutionContext) {

var success = true
var lastErrorMessage = ""

try {
executeAwareTimed(context)
} catch (e: Exception) {

logger.error("Error in job", e)

success = false
lastErrorMessage = e.message ?: "Unknown error"
}

val lastFireTime = context.fireTime
val lastFinishTime = Date.from(Instant.now())
val lastDuration = lastFinishTime.time - lastFireTime?.time!!

context.jobDetail.jobDataMap["lastFireTime"] = lastFireTime
context.jobDetail.jobDataMap["lastFinishTime"] = lastFinishTime
context.jobDetail.jobDataMap["lastDuration"] = lastDuration
context.jobDetail.jobDataMap["lastSuccess"] = success
context.jobDetail.jobDataMap["lastErrorMessage"] = lastErrorMessage
context.jobDetail.jobDataMap["executionId"] = UUID.randomUUID().toString()

}

abstract fun executeAwareTimed(context: JobExecutionContext)

}
9 changes: 8 additions & 1 deletion src/main/kotlin/com/valensas/simplyquartz/TimedJob.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,18 @@ import io.micrometer.core.instrument.Metrics
import io.micrometer.core.instrument.Timer
import org.quartz.Job
import org.quartz.JobExecutionContext
import org.quartz.PersistJobDataAfterExecution
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import kotlin.time.measureTimedValue
import kotlin.time.toJavaDuration

abstract class TimedJob : Job {

private val timers = mutableMapOf<String, Timer>()

private var logger = LoggerFactory.getLogger(this.javaClass.name)

override fun execute(context: JobExecutionContext) {
val result = measureTimedValue { kotlin.runCatching { executeTimed(context) } }

Expand All @@ -32,7 +37,9 @@ abstract class TimedJob : Job {
}

timer.record(result.duration.toJavaDuration())

logger.info("Job $jobName-$jobGroup executed in ${result.duration}")
}

protected abstract fun executeTimed(context: JobExecutionContext?)
protected abstract fun executeTimed(context: JobExecutionContext)
}

0 comments on commit adef59e

Please sign in to comment.