【问题标题】:Run coroutine inside @Scheduled在@Scheduled 中运行协程
【发布时间】:2021-08-24 02:48:52
【问题描述】:

我想运行一个周期性任务。在 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
}

【问题讨论】:

    标签: spring spring-boot kotlin spring-webflux kotlin-coroutines


    【解决方案1】:
    fun myScheduler() {
        runBlocking {
            mySuspendedFunction()
        }
    }
    

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

    【讨论】:

      猜你喜欢
      • 2019-12-18
      • 2020-09-04
      • 1970-01-01
      • 1970-01-01
      • 2018-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多