runWithTimeout

fun <T> runWithTimeout(timeoutSeconds: Int?, onTimeout: (ExecutionTimeoutException) -> T? = null, action: () -> T): T

Runs action with an optional timeout. If timeoutSeconds is null or non-positive, action is executed directly on the current thread. Otherwise, it is submitted and bounded by the given duration.

Return

the result of action, or the result of onTimeout if the timeout fires

Parameters

timeoutSeconds

maximum allowed seconds, or null to disable

onTimeout

optional handler invoked when the timeout is exceeded. If null, the ExecutionTimeoutException is thrown instead.

action

the computation to run

Throws

if the timeout is exceeded and onTimeout is not provided