在 @Scheduled 内运行协程

Tie*_*Nam 4 spring kotlin spring-boot spring-webflux kotlin-coroutines

我想运行一个周期性任务。在 Spring MVC 中它可以完美地工作。现在我想集成 Spring Webflux + Kotlin 协程。如何在@Scheduled方法中调用挂起的函数?我希望它等到挂起的功能完成。

/// This function starts every 00:10 UTC
@Scheduled(cron = "0 10 0 * * *", zone = "UTC")
fun myScheduler() {
    // ???
}

suspend fun mySuspendedFunction() {
    // business logic
}
Run Code Online (Sandbox Code Playgroud)

bro*_*oot 10

fun myScheduler() {
    runBlocking {
        mySuspendedFunction()
    }
}
Run Code Online (Sandbox Code Playgroud)

这样协程将在被阻塞的线程中运行。如果您需要在不同的线程中运行代码或并行执行多个协程,您可以将调度程序(例如Dispatchers.DefaultDispatchers.IO)传递给runBlocking()或使用withContenxt()