运行 Scala 猫后台线程上的 IO
Running IO on background thread in scala cats
def backGroundTask:IO[Unit]={
IO
{
//Time consuming task
}
}
如何在后台线程中急切执行此任务?
您可以使用 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]
def backGroundTask:IO[Unit]={
IO
{
//Time consuming task
}
}
如何在后台线程中急切执行此任务?
您可以使用 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]