kotlinkotlin-coroutinesktorcoroutinescope

Ktor: launch long-running task then immediately send HTTP response


How do I properly launch a long-running task in Ktor sever without waiting for its completion, i.e. launch and immediately send the HTTP response back.

In this answer: https://stackoverflow.com/a/73930834/12570695

Something like this is suggested:


CoroutineScope(Dispatchers.IO).launch { 
        // long-running task
}

However, in this answer: https://stackoverflow.com/a/75843232

This approach is highly discouraged because it creates an unmanaged coroutine scope.

How to do it properly?


Solution

  • I think I found an answer. Based on this documentation: https://api.ktor.io/ktor-server/ktor-server-core/io.ktor.server.application/-application/index.html

    "Represents configured and running web application, capable of handling requests. It is also the application coroutine scope that is cancelled immediately at application stop so useful for launching background coroutines."

    Based on this, I assume the correct approach would be:

    routing {
        get("/") {
            call.application.launch(Dispatcher.IO) {
                //Long running task
            }
        }
    }