@@ -8,24 +8,17 @@ import io.ktor.server.application.ApplicationStopping
8
8
import io.ktor.server.application.createApplicationPlugin
9
9
import io.ktor.server.application.hooks.MonitoringEvent
10
10
import io.ktor.server.application.log
11
- import kotlinx.coroutines.CoroutineDispatcher
12
- import kotlinx.coroutines.Dispatchers
13
- import kotlinx.coroutines.Job
14
- import kotlinx.coroutines.launch
15
- import org.slf4j.LoggerFactory
11
+ import no.nav.paw.async.runner.ScheduledAsyncRunner
16
12
import java.time.Duration
17
- import java.util.*
18
13
19
- private val logger = LoggerFactory .getLogger(" no.nav.paw.logger.scheduling" )
20
14
private const val PLUGIN_NAME_SUFFIX = " ScheduledTaskPlugin"
21
15
22
16
class ScheduledTaskPluginConfig {
23
17
var task: (() -> Unit )? = null
18
+ var interval: Duration ? = null
24
19
var delay: Duration ? = null
25
- var period: Duration ? = null
26
20
var startEvent: EventDefinition <Application >? = null
27
21
var stopEvent: EventDefinition <Application >? = null
28
- var coroutineDispatcher: CoroutineDispatcher ? = null
29
22
}
30
23
31
24
@Suppress(" FunctionName" )
@@ -34,30 +27,18 @@ fun ScheduledTaskPlugin(pluginInstance: Any): ApplicationPlugin<ScheduledTaskPlu
34
27
return createApplicationPlugin(pluginName, ::ScheduledTaskPluginConfig ) {
35
28
application.log.info(" Installerer {}" , pluginName)
36
29
val task = requireNotNull(pluginConfig.task) { " Task er null" }
30
+ val interval = requireNotNull(pluginConfig.interval) { " Interval er null" }
37
31
val delay = requireNotNull(pluginConfig.delay) { " Delay er null" }
38
- val period = requireNotNull(pluginConfig.period) { " Period er null" }
39
32
val startEvent = pluginConfig.startEvent ? : ApplicationStarted
40
33
val stopEvent = pluginConfig.stopEvent ? : ApplicationStopping
41
- val coroutineDispatcher = pluginConfig.coroutineDispatcher ? : Dispatchers .IO
42
- var job: Job ? = null
43
- val timer = Timer ()
44
- val timerTask = object : TimerTask () {
45
- override fun run () {
46
- logger.info(" Running scheduled task {}" , pluginInstance)
47
- task()
48
- }
49
- }
34
+ val asyncRunner = ScheduledAsyncRunner <Unit >(interval, delay)
50
35
51
- on(MonitoringEvent (startEvent)) { application ->
52
- application.log.info(" Scheduling task {} at delay: {}, period {}" , pluginInstance, delay, period)
53
- job = application.launch(coroutineDispatcher) {
54
- timer.scheduleAtFixedRate(timerTask, delay.toMillis(), period.toMillis())
55
- }
36
+ on(MonitoringEvent (startEvent)) {
37
+ asyncRunner.run (task, {}) {}
56
38
}
57
39
58
- on(MonitoringEvent (stopEvent)) { _ ->
59
- application.log.info(" Canceling scheduled task {}" , pluginInstance)
60
- job?.cancel()
40
+ on(MonitoringEvent (stopEvent)) {
41
+ asyncRunner.abort {}
61
42
}
62
43
}
63
44
}
0 commit comments