简体   繁体   中英

Kotlin withTimeout does not work in Intellij gradle project

Run following code give me the wrong results:

code

import kotlinx.coroutines.*

fun timeElapsed(nano: Long, msg: String){
    println("$msg milliseconds: ${(System.nanoTime()-nano)/1000000}")
}
suspend fun main(): Unit = coroutineScope {
    val start = System.nanoTime()
    withTimeout(700) { 
        println("in timout")
        timeElapsed(start, "timeout before delay")
        delay(900)
        println("not show?")
    }
}

wrong result

in timout
timeout before delay milliseconds: 16
not show?
Exception in thread "main" kotlinx.coroutines.TimeoutCancellationException: Timed out waiting for 700 ms

run on https://play.kotlinlang.org/ give me the expected result:

in timout
timeout before delay milliseconds: 27
Exception in thread "main" kotlinx.coroutines.TimeoutCancellationException: Timed out waiting for 700 ms

My gradle setup

plugins {
    id 'org.jetbrains.kotlin.jvm' version '1.6.21'
    id 'org.jetbrains.kotlin.plugin.serialization' version '1.6.21'
}

group 'intro-coroutines'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib"
    implementation "org.jetbrains.kotlin:kotlin-reflect"
    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.2.2")

    def coroutines_version = '1.6.1'
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-swing:$coroutines_version"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:$coroutines_version"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-slf4j:$coroutines_version"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-debug:$coroutines_version"

Intellij version: Build #IU-221.5080.210, built on April 11, 2022

kotline plugin version: 221-1.7.0-Beta-release-135-IJ5080.210

Java SDK: JavaSE-1.8

what could possibly go wrong?

finally, I figured out why, totally my fault:

I define a delay() function in another Kotlin file in the same package as follows:

suspend fun delay(timeMillis: Long): Unit =
    suspendCoroutine { cont ->
        executor.schedule({
            cont.resume(Unit)
        }, timeMillis, TimeUnit.MILLISECONDS)
    }

As this continuation is a non-cancellable one, so delay is not cancellable, Sorry: lesson learned, function should be private, and check the import!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM