如何在 Ktor 微服务应用中调度任务
How to schedule tasks in Ktor microservice app
我正在尝试在我的 Ktor 应用程序中安排任务,但是我无法在网上找到有关如何执行此操作的任何信息。有没有人有任何建议或以前能够做到这一点?
Ktor 没有内置的调度器,所以你必须自己实现
我已经使用 Java 的执行器为我自己编写了一些小的 class,您可能会发现它很有用
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)
我正在尝试在我的 Ktor 应用程序中安排任务,但是我无法在网上找到有关如何执行此操作的任何信息。有没有人有任何建议或以前能够做到这一点?
Ktor 没有内置的调度器,所以你必须自己实现
我已经使用 Java 的执行器为我自己编写了一些小的 class,您可能会发现它很有用
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)