Sobes.tech
Junior — Middle

Kuidas seada oma projektis korutinate täitmisaja piirang?

sobes.tech AI

Vastus AI-lt

To limit the execution time of coroutines in Kotlin, you can use the withTimeout or withTimeoutOrNull functions from the kotlinx.coroutines library. These allow you to set a maximum execution time for a block of code, and if the coroutine does not finish within this time, a TimeoutCancellationException will be thrown or null will be returned, respectively.

Example:

import kotlinx.coroutines.*

fun main() = runBlocking {
    try {
        withTimeout(1000L) { // limit of 1000 milliseconds
            repeat(5) { i ->
                println("Iteration $i")
                delay(300L) // simulate work
            }
        }
    } catch (e: TimeoutCancellationException) {
        println("Execution time has expired")
    }
}

This way, you can control the duration of coroutines and prevent hangs or operations that take too long.