0

我想定义一个可以与 Akka 演员混合的特征,该演员在一段时间后安排接收超时。这是我想要做的草图......

trait BidderInActivityClearingSchedule[T <: Tradable, A <: Auction[T, A]]
    extends ClearingSchedule[T, A] {
  this: AuctionActor[T, A] =>

  context.setReceiveTimeout(timeout)  // can I call this here?

  def timeout: FiniteDuration

  override def receive: Receive = {
    case ReceiveTimeout =>
      val (clearedAuction, contracts) = auction.clear
      contracts.foreach(contract => settlementService ! contract)
      auction = clearedAuction
    case message => this.receive(message)
  }

}


class FancyAuctionActor[T <: Tradable](val timeout: FiniteDuration, ...)
    extends AuctionActor[T, FancyAuctionActor[T]]
    with BidderInActivityClearingSchedule[T, FancyAuctionActor[T]]

...但我不明白什么时候context.setReceiveTimeout会被调用。调用时会作为构造函数的一部分MyFancyAuctionActor调用吗?timeout或者它会更早被调用,因此由于尚未定义的事实而引发某种错误。

4

2 回答 2

0

我建议使用演员的生命周期事件挂钩来控制您的日程安排的触发。如果您的 trait 扩展了这样的演员:

trait AuctionActor[T, A] extends Actor
trait BidderInActivityClearingSchedule[T, A] extends AuctionActor[T,A] 

您将可以访问参与者的许多生命周期事件挂钩,例如preStart()postStop()等等。

所以你可以很容易地做到:

trait BidderInActivityClearingSchedule[T, A] extends AuctionActor[T,A] {
  override def preStart() = {
    supre.preStart() // or call this after the below line if must.
    context.setReceiveTimeout(timeout)  // can I call this here?
  }    
}

更新

如果你想实现一个可堆叠的 mixins 结构。你会做与上面类似的事情。

//your AuctionActor is now a class as you wanted it
class AuctionActor[T, A] extends Actor

//Look below; the trait is extending a class! it's ok! this means you can 
//only use this trait to extend an instance of AuctionActor class 
trait BidderInActivityClearingSchedule[T, A] extends AuctionActor[T,A]{
  def timeout: FiniteDuration

  //take note of the weird "abstract override keyword! it's a thing!"
  abstract override def preStart() = {
    super.preStart()
    context.setReceiveTimeout(timeout)
  }
}

您可以将扩展类 AuctionActor 的许多特征堆叠在一起。

于 2017-07-18T13:37:24.940 回答
0

您可以使用自我类型来要求仅将特征混合到 Actors 中。

trait MyMixin { self: Actor =>
  println(self.path)
}

trait MyActor extends Actor with MyMixin

MyMixin不是一个演员,但它只能由作为演员的类扩展。

于 2017-07-18T15:30:10.077 回答