Run coroutine inside @Scheduled

Viewed 1362

I want to run a periodic task. In Spring MVC it works flawlessly. Now I want to integrate Spring Webflux + Kotlin Coroutines. How can I call suspended functions in the @Scheduled method? I want it to wait until the suspended function is finished.

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

suspend fun mySuspendedFunction() {
    // business logic
}
1 Answers
fun myScheduler() {
    runBlocking {
        mySuspendedFunction()
    }
}

This way coroutines will run in the thread that was blocked. If you need to run the code in a different thread or execute several coroutines in parallel, you can pass a dispatcher (e.g. Dispatchers.Default, Dispatchers.IO) to runBlocking() or use withContenxt().

Related