scala - 模拟时间和 Akka 调度器

标签 scala akka scheduler

我正在使用 Akka 构建多代理模拟,因此希望以比实时更快的速度运行模拟。具体来说,我想配置 Akka 调度程序,以便调度程序从一个预定的事件前进到下一个(这显然可能涉及事件之间的明显不同的时间步长),而不是按一些潜在的固定时间步长前进。

稍有不同,我希望调度程序表现得好像它是一种优先级队列,其中优先级由事件的模拟时间戳给出。

这清楚吗?如果是这样,我想使用 Actor 系统的默认调度程序来做什么?如果这是不可能的,那么我将如何使用现有的 Akka 组件滚动我自己的调度程序来完成此任务。

最佳答案

我认为 akka 调度程序不可能做到这一点。来自 documentation (强调我的):

Sometimes the need for making things happen in the future arises, and where do you go look then? Look no further than ActorSystem! There you find the scheduler method that returns an instance of akka.actor.Scheduler, this instance is unique per ActorSystem and is used internally for scheduling things to happen at specific points in time.



但是,您始终可以使用递归函数完成相同的事情。假设您的“实时”功能如下所示:
def periodicFunction() : Unit = ???  //whatever you're doing to Agents

//periodicFunction is called every 10 seconds
actorSystem.scheduler().schedule(0 seconds, 10 seconds)(periodicFunction())

您的模拟代码可能只是:
@scala.annotation.tailrec
def fasterThanRealTimeLoop(n : Int) = 
  if(n > 0) {
    periodicFunction()

    fasterThanRealTimeLoop(n-1)
  }

然后你可以模拟 20 次运行
fasterThanRealTimeLoop(20)

可以进一步包装此功能以封装两种可能性:
val realtimeMode : Boolean = ??? //some configuration setting

val periodicArgs : Either[FiniteDuration, Int] = 
  if(realtimeMode) Left(10 Seconds) else Right(20)

periodicArgs.left.foreach { period => 
  actorSystem.scheduler().schedule(0 seconds, period)(periodicFunction())
}

periodicArgs.right.foreach { count => 
  fasterThanRealTimeLoop(count)
}

此代码现在将根据配置设置调用正确类型的循环(定时或尽可能快)。

关于scala - 模拟时间和 Akka 调度器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33915856/

相关文章:

cocos2d-iphone - nsmutablearray 在调用时不添加对象

scala - 我一般如何处理 Scala 集合?

scala:如何链接不同类型的部分函数

scala - 在 casbah 的 find() 查询中使用 $in

playframework - 如何在关机时停止 akka 线程

Akka Streams : What does Mat represents in Source[out, Mat]

java - 同步(或 future 返回)调用 Akka UntypedPersistentActor?

python - pytorch 中的 ReduceLrOnPlateau 调度程序可以使用测试集度量来降低学习率吗?

python - 在 Azure 上安排 python 脚本

java - 正则表达式 - 除了给定单词之外的所有有效标识符?