我想运行一个周期性任务。在 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
}
fun myScheduler() {
runBlocking {
mySuspendedFunction()
}
}
这样协程将在被阻塞的线程中运行。如果您需要在不同的线程中运行代码或并行执行多个协程,您可以将调度程序(例如
Dispatchers.Default
、Dispatchers.IO
)传递给 runBlocking()
或使用 withContenxt()
。
从 Spring 6.1 开始,支持 ootb。
@Scheduled(cron = "0 10 0 * * *", zone = "UTC")
suspend fun myScheduler() {
mySuspendedFunction()
}