Kotlin Coroutines-无需等待即可在API呼叫和返回API呼叫中启动功能

发布于 2025-01-21 10:03:11 字数 451 浏览 3 评论 0原文

我有一个API电话,我想开始长时间的运行工作,然后再返回200。目前,它将开始工作并继续前进,但是一旦初始功能完成了需要做的事情,它似乎仍然等到Coroutine完成。我敢肯定,这与我对Kotlin Coroutines相对较新的理解有关。

fun apiCall() {
   log.info("started")
   longJob()
   log.info("finished")
   
   return ResponseEntity.ok()
}

fun longJob() {
   runBlocking{
      launch {
        do stufff...
      }
   }
}

因此,基本上,我希望看到日志打印,然后启动Longjob,然后在Postman中看到200。但是实际上,我已经打印出了两个日志,而且工作开始了,但是直到工作完成之前,我才看到我的200ok。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

飞烟轻若梦 2025-01-28 10:03:11

如果我正确理解,您想在后台启动longjob,然后返回200ok状态,而无需等待longjob完成。如果是这种情况,那么您不能在此处使用runblocking,它会阻止当前线程,直到所有作业都在其中启动,完成。您可以创建一个coroutinescope,然后启动并忘记长期运行的任务。示例代码:

val scope = CoroutineScope(Dispatchers.IO) // or CoroutineScope(Dispatchers.IO + SupervisorJob())

fun apiCall() {
   log.info("started")
   scope.launch { longJob() }
   log.info("finished")
   
   return ResponseEntity.ok()
}

在此示例日志中,“启动”和“完成”将在longjob()开始执行之前打印。

If I understand correctly, you want to launch the longJob in background, and return 200ok status without waiting for longJob to finish. If this is the case then you can't use runBlocking here, it blocks the current thread until all jobs, launched in it, finish. You can create a CoroutineScope and launch and forget a long running task. The sample code:

val scope = CoroutineScope(Dispatchers.IO) // or CoroutineScope(Dispatchers.IO + SupervisorJob())

fun apiCall() {
   log.info("started")
   scope.launch { longJob() }
   log.info("finished")
   
   return ResponseEntity.ok()
}

In this sample logs "started" and "finished" will be printed before longJob() starts executing.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文