Run coroutine inside @Scheduled
Asked Answered
L

2

6

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
}
Lundy answered 6/6, 2021 at 23:37 Comment(0)
G
12
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().

Geographical answered 6/6, 2021 at 23:45 Comment(0)
S
3

Since Spring 6.1, this is supported 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()
}
Speck answered 10/4 at 11:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.