Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to schedule tasks in Ktor microservice app

I am trying to schedule a task in my Ktor application, however I have not been able to find anything online about how to do this. Does anyone have any recommendations or been able to do this before?

like image 975
Anesh P. Avatar asked Nov 05 '19 18:11

Anesh P.


1 Answers

Ktor doesn't have built-in scheduler, so you'd have to implement your own

I've written small class using Java's Executors for this task for myself, you might find it useful

class Scheduler(private val task: Runnable) {
    private val executor = Executors.newScheduledThreadPool(1)!!

    fun scheduleExecution(every: Every) {

        val taskWrapper = Runnable {
            task.run()
        }

        executor.scheduleWithFixedDelay(taskWrapper, every.n, every.n, every.unit)
    }


    fun stop() {
        executor.shutdown()

        try {
            executor.awaitTermination(1, TimeUnit.HOURS)
        } catch (e: InterruptedException) {
        }

    }
}

data class Every(val n: Long, val unit: TimeUnit)
like image 173
Evgeny Bovykin Avatar answered Nov 05 '22 10:11

Evgeny Bovykin