如果
flag
设置为 true,我需要按时间间隔运行 IO 操作。可以在一个时间间隔内从程序的其他位置多次将标志设置为 true。例如:
class IntervalAction {
def touch: IO[Unit] // set flag to true
// if flag is true, on interval do action and set flag to false
}
class Service(action: IntervalAction) {
def run = {
1 to 100 traverse { i =>
if (i % 2 == 0) action.touch()
}
}
}
如何使用cat 实现IntervalAction 内部调度程序、间隔处理程序、异步标志处理程序等?
你的代码几乎是正确的,我们只需要告诉它当条件为假时该怎么做:
1 to 100 traverse { i =>
if (i % 2 == 0) action.touch()
else IO.unit
}
或者使用更方便的方法:
1 to 100 traverse { i =>
IO.whenA(i % 2 == 0)(action.touch())
}
我带着这个解决方案
def backgroundTest: IO[Unit] = {
var flag = false // probably ok that it is thread-unsafe
def backgroundInterval: IO[Unit] = {
IO.println("Interval started") *>
IO.sleep(3.seconds).flatMap { _ =>
println(s"3 seconds elapsed flag is: ${flag}")
flag = false
backgroundInterval
}.void
}
def innerRequestHandler: IO[Unit] = {
for {
_ <- Console[IO].println("Write something")
_ <- Console[IO].readLine
.flatMap { line =>
if (line == "q") IO.unit
else {
flag = true
innerRequestHandler
}
}
} yield ()
}
backgroundInterval.background.use { _ =>
innerRequestHandler
}
}