简体   繁体   English

在Scala Cat中的后台线程上运行IO

[英]Running IO on background thread in scala cats

def backGroundTask:IO[Unit]={
IO
{
//Time consuming task
}
}

How to execute this task eagerly on a background thread? 如何在后台线程上急切地执行此任务?

You can use ContextShift.evalOn : 您可以使用ContextShift.evalOn

def backGroundTask = IO {
      Thread.currentThread()
}

val contextShift: ContextShift[IO] = IO.contextShift(ExecutionContext.global)

val ec = ExecutionContext.fromExecutor(Executors.newCachedThreadPool()) //create other execution context

println(backGroundTask.unsafeRunSync()) // will print Thread[main,5,main]
println(contextShift.evalOn(ec)(backGroundTask).unsafeRunSync()) //will print Thread[pool-1-thread-1,5,main]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM