/**
* 超时任务
*/
@Test
fun `test deal with timeout`() = runBlocking<Unit> {
withTimeout(1300) {
repeat(1000) { i ->
println("job:I'm sleeping $i ...")
delay(500)
}
}
}
时间不够会自动抛出异常退出
可以使用withnull拿到结果
/**
* 超时任务
*/
@Test
fun `test deal with timeout return null`() = runBlocking<Unit> {
//时间不够会自动抛出异常退出
val res=withTimeoutOrNull(1300) {
repeat(2) { i ->
println("job:I'm sleeping $i ...")
delay(500)
}
"done"
}
println(res)
}
2次的重复肯定是返回done 如果三次则返回null