12-协程超时
12.3.6 协程超时
在实际开发中,取消协程执行的一个原因是其任务的执行已经超时,当然也可以使用withTimeout函数来给协程设定一个最大执行时间,超出时间就直接终止执行。
fun timeouts() = runBlocking<Unit> {
withTimeout(3000L) {
repeat(100) { i ->
println("I'm sleeping $i ...")
delay(500L)
}
}
}
如果直接运行上面的代码会抛出一个TimeoutCancellationException异常,由withTimeout抛出的异常是CancellationException的一个私有子类。之所以没有打印CancellationException相关的错误信息,是因为取消协程被看作是一个正常的操作。如果需要在超时的时候执行一些附加操作,则可以使用try {} catch () {}来处理withTimeout抛出的异常。
try {
timeouts()
} catch (e: CancellationException) {
println("CancellationException:${e}")
}