9

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?

Anesh P.
  • 155
  • 1
  • 7

1 Answers1

6

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

I've written a 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)
th0bse
  • 97
  • 8
Evgeny Bovykin
  • 2,572
  • 2
  • 14
  • 27
  • awesome this works. Currently I am starting the Runnable when an api call is made. Is there a way to have the runnable running at all times? – Anesh P. Nov 05 '19 at 21:31
  • Could you please elaborate on what you mean by "runnable running at all times"? You mean as soon as you create `Scheduler`? You could create `init {}` block and `scheduleExecution` in it – Evgeny Bovykin Nov 06 '19 at 06:48
  • 2
    Evgeny, please provide how to call it from running thread – Eshan I. Jun 28 '20 at 12:34