I’m trying to make a function which triggers a possibly slow operation which can’t be cancelled. I want this operation to run in a coroutine with a timeout. Since the operation cannot be cancelled as mentioned before, I need the function to return after the time out, but the operation to stay in the background.
The code I have been trying to get working runs a lengthy operation of 10 seconds asynchronously which has a time out of 5 seconds, so therefore the function should return after the timeout and let main continue its job, printing “foo execution finished”, and finally 5 more seconds later the slow job would print “job ends (10 seconds passed)”.
Here’s the code:
fun main() {
println("program execution begins")
foo()
println("foo execution finished")
while(true);
}
fun foo() = runBlocking {
val job = async {
val endTimeMillis = System.currentTimeMillis() + (10 * 1000)
while (System.currentTimeMillis() <= endTimeMillis); //blocks for 10 seconds
println("job ends (10 seconds passed)")
}
try {
withTimeout(5000) {
println("start awaiting with 5 secs timeout")
job.await()
}
} catch (ex: TimeoutCancellationException) {
println("out of time")
}
}
Which then produces the following result:
program execution begins
start awaiting with 5 secs timeout
job ends (10 seconds passed)
out of time
foo execution finished
But this is not exactly the behavior I need in this case as mentioned before. I need to make it so that output looks something like:
program execution begins
start awaiting with 5 secs timeout
out of time
foo execution finished
job ends (10 seconds passed)
In addition to this, I can’t use any sort of “kotlin-coroutines” function in the async to archive this behavior, since the code called in there will be user code unrelated to the coroutine, possibly written in Java. hence the while loop for blocking the async block instead of a delay() in the sample.
Thanks in advance for the help!