Scala中的未来和无限循环

时间:2016-02-13 20:01:40

标签: scala concurrency future

我想在scala中执行2个独立的无限循环。第一项任务每次运行大约需要1秒钟,第二项任务需要0.5秒。

以下是代码:

package future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}

object MyFuture {
  def task1(): Future[Unit] = Future {
    println("doing job 1")
    Thread.sleep(1000)
  }

  def task2(): Future[Unit] = Future {
    println("doing job 2")
    Thread.sleep(500)
  }

  def infiniteLoop(): Future[Unit] = {
    Future.sequence(List(task1(), task2())).flatMap(x => infiniteLoop())
  }

  def main(args: Array[String]): Unit = {

    Await.ready(infiniteLoop(), Duration.Inf)
  }

}

程序的输出

doing job 1
doing job 2
doing job 2
doing job 1
doing job 1
doing job 2
doing job 1
doing job 2
doing job 1
doing job 2
doing job 1
doing job 2
doing job 1
doing job 2
doing job 1
doing job 2
doing job 1
doing job 2

我希望作业2的输出是作业1的输出的两倍,因为它需要一半的时间。

我可以做些什么来模拟2个真正的独立过程?

1 个答案:

答案 0 :(得分:3)

考虑使用java' scheduled executor来安排固定间隔的任务。或者,如果您需要在此任务之间进行通信,则可以使用Akka。 顺便说一下,这段代码可以满足您的要求:

SELECT ITEM,
    -- The CID is used inside the case, inside the count function.
    -- NULL will not be included in the count
    COUNT(DISTINCT CASE WHEN FLAG = 1 THEN CID ELSE NULL END) AS COUNTER 
    from T 
    group by ITEM