在@Scheduled内运行协程

问题描述 投票:0回答:2

我想运行一个周期性任务。在 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
}
spring spring-boot kotlin spring-webflux kotlin-coroutines
2个回答
10
投票
fun myScheduler() {
    runBlocking {
        mySuspendedFunction()
    }
}

这样协程将在被阻塞的线程中运行。如果您需要在不同的线程中运行代码或并行执行多个协程,您可以将调度程序(例如

Dispatchers.Default
Dispatchers.IO
)传递给
runBlocking()
或使用
withContenxt()


0
投票

从 Spring 6.1 开始,支持 ootb。

https://docs.spring.io/spring-framework/reference/integration/scheduling.html#scheduling-annotation-support-scheduled-reactive

@Scheduled(cron = "0 10 0 * * *", zone = "UTC")
suspend fun myScheduler() {
    mySuspendedFunction()
}
© www.soinside.com 2019 - 2024. All rights reserved.