运行 @Scheduled 内的协程
Run coroutine inside @Scheduled
我想运行一个周期性任务。在 Spring MVC 中,它可以完美运行。
现在我想整合 Spring Webflux + Kotlin Coroutines。
如何调用 @Scheduled
方法中的挂起函数?我想让它等到挂起的函数完成。
/// This function starts every 00:10 UTC
@Scheduled(cron = "0 10 0 * * *", zone = "UTC")
fun myScheduler() {
// ???
}
suspend fun mySuspendedFunction() {
// business logic
}
fun myScheduler() {
runBlocking {
mySuspendedFunction()
}
}
这样协程将 运行 在被阻塞的线程中。如果您需要 运行 不同线程中的代码或并行执行多个协程,您可以将调度程序(例如 Dispatchers.Default
、Dispatchers.IO
)传递给 runBlocking()
或使用 withContenxt()
.
我想运行一个周期性任务。在 Spring MVC 中,它可以完美运行。
现在我想整合 Spring Webflux + Kotlin Coroutines。
如何调用 @Scheduled
方法中的挂起函数?我想让它等到挂起的函数完成。
/// This function starts every 00:10 UTC
@Scheduled(cron = "0 10 0 * * *", zone = "UTC")
fun myScheduler() {
// ???
}
suspend fun mySuspendedFunction() {
// business logic
}
fun myScheduler() {
runBlocking {
mySuspendedFunction()
}
}
这样协程将 运行 在被阻塞的线程中。如果您需要 运行 不同线程中的代码或并行执行多个协程,您可以将调度程序(例如 Dispatchers.Default
、Dispatchers.IO
)传递给 runBlocking()
或使用 withContenxt()
.