我正在尝试处理一些任务。任务所花费的时间可能因元素而异。例如,1
从队列中存储和获取元素可能需要 11 秒,而2
可能需要 30 秒......
我已经尝试为此使用计时器,但我仍然得到 entryTime = ExitTime 我想知道我错过了什么。
这是我尝试过的:
import cats.effect.{ExitCode, IO, IOApp, Timer}
import fs2._
import fs2.concurrent.Queue
import scala.concurrent.duration._
import scala.util.Random
class Tst(q1: Queue[IO, (Double, String, String)])(implicit timer: Timer[IO]) {
import core.Processing._
def storeInQueue: Stream[IO, Unit] = {
Stream(1, 2, 3)
.covary[IO]
.evalTap(n => IO.delay(println(s"Pushing $n to Queue")))
.map { n =>
val entryTime = currentTimeNow
(n.toDouble, "Service", entryTime)
// timer.sleep(Random.between(10, 30).seconds) I have tried adding it here but the same result
}
.through(q1.enqueue)
}
def getFromQueue: Stream[IO, Unit] = {
timer.sleep(Random.between(10, 30).seconds)
q1.dequeue
.map { n =>
val exitTime = currentTimeNow
(n._1, "Service", n._3, exitTime)
}
.evalMap(n => IO.delay(println(s"Pulling from queue $n")))
}
}
object Five2 extends IOApp {
override def run(args: List[String]): IO[ExitCode] = {
val program = for {
q <- Queue.bounded[IO, (Double, String, String)](10)
b = new Tst(q)
_ <- b.storeInQueue.compile.drain.start
_ <- b.getFromQueue.compile.drain
} yield ()
program.as(ExitCode.Success)
}
}
currentTimeNow 方法给出:
def currentTimeNow: String = {
val format = new SimpleDateFormat("dd-MM-yy hh:mm:ss")
format.format(Calendar.getInstance().getTime())
}