I have an api call that I want to kick off a long running job and then return a 200 ok. Currently it will kick of the job and move on, but once the initial function finishes what it needs to do, it still seems to wait until the coroutine has finished. I'm sure this is related to my relatively new understanding of kotlin coroutines.
fun apiCall() {
log.info("started")
longJob()
log.info("finished")
return ResponseEntity.ok()
}
fun longJob() {
runBlocking{
launch {
do stufff...
}
}
}
So basically I'm expected to see the logs print and then kick off the longJob and then see 200 in postman. But I'm actually getting both logs printed out as well as the job kicked off, but I don't see my 200ok until the job finishes.
If I understand correctly, you want to launch the
longJob
in background, and return200ok
status without waiting forlongJob
to finish. If this is the case then you can't userunBlocking
here, it blocks the current thread until all jobs, launched in it, finish. You can create aCoroutineScope
and launch and forget a long running task. The sample code:In this sample logs "started" and "finished" will be printed before
longJob()
starts executing.