Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Coroutine - is there a default timeout

I'm trying to reach a server, which is occasionally slow. The ktor client I'm using is crashing with an Exception in thread "main" kotlinx.coroutines.TimeoutCancellationException: Timed out waiting for 15000 ms, even though I never specified any limit. Is there a default timeout integrated?

Minimal example:

main.kt

import io.ktor.client.engine.cio.*
import io.ktor.client.features.*
import io.ktor.client.request.*


suspend fun main() {
    val client = HttpClient(CIO) {
        install(HttpTimeout) {
            requestTimeoutMillis = HttpTimeout.INFINITE_TIMEOUT_MS
            connectTimeoutMillis = HttpTimeout.INFINITE_TIMEOUT_MS
            socketTimeoutMillis = HttpTimeout.INFINITE_TIMEOUT_MS
        }
    }

    val foo = client.get<String>("http://slowwly.robertomurray.co.uk/delay/20000/url/http://www.google.co.uk")
    println(foo)

}

build.gradle.kts

import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
    kotlin("jvm") version "1.4.10"
    application
}
group = "me.oehmj"
version = "1.0-SNAPSHOT"

repositories {
    mavenCentral()
}

val ktor_version: String by project
val kotlin_serialization_version: String by project
val kotlin_coroutines_version: String by project

dependencies {
    implementation("io.ktor:ktor-client-cio:$ktor_version")
    implementation("io.ktor:ktor-client-auth-jvm:$ktor_version")
    implementation("io.ktor:ktor-client-logging-jvm:$ktor_version")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlin_coroutines_version")
}

tasks.withType<KotlinCompile>() {
    kotlinOptions.jvmTarget = "1.8"
}
application {
    mainClassName = "MainKt"
}

gradle.properties

kotlin.code.style=official
ktor_version=1.4.2
kotlin_coroutines_version=1.4.1

The Ktor-HttpTimeout-Module seems to have no effect. Are there any suggestions on how I can prolong the Timeout time?

like image 707
Johannes Oehm Avatar asked May 21 '26 03:05

Johannes Oehm


2 Answers

Looking at the documentation you should do like that:

val client = HttpClient(CIO) {
    engine {
        requestTimeout = 0 // 0 to disable, or a millisecond value to fit your needs
    }
}

The default value is 15 seconds.

You can read more about ktor engines here

enter image description here

like image 74
shadowsheep Avatar answered May 24 '26 00:05

shadowsheep


It's working for me:

return HttpClient(CIO) {
    install(HttpTimeout) {
        this.requestTimeoutMillis = 15000
    }
}
like image 28
李其鹏 Avatar answered May 24 '26 00:05

李其鹏



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!