Skip to content

Simulation hooks

Romain Franceschini edited this page Apr 27, 2020 · 4 revisions

Quartz issues several events during simulation that are related to the simulation state itself and that we refer as hooks.

A publish/subscribe pattern is used so that third-party objects may be informed to one or more of the following events, depending on what they subscribed for:

  • before/after simulation is initialized
  • before/after simulation execution
  • before/after simulation abandon (via an error or a cancellation)
  • before/after simulation is restarted

Those events can be useful at many different levels. For example, the modeler can use them in its models to prepare or cleanup resources before and after a simulation (e.g. open or closing a file).

Note that no events are issued each time there is a simulation tick for performance reasons. However, it is possible to execute a simulation step-by-step.

Being notified

A Notifier provides a mechanism for broadcasting hooks during simulation. An instance can be associated during Simulation initialization (Simulation#notifier) so that objects can register to hooks. Otherwise, a default instance is provided with a Simulation.

Hooks can be dispatched either to Procs or to Notifiable objects. They can register to a hook using the #subscribe method. Each invocation of this method registers the receiver to a given hook. Therefore, objects may register to several hooks.

The Notifiable module is intended to be included in a class as a mixin. It provides an interface so that objects can register and receive hooks through the #notify method.

Allowed events to register for are:

  • Hooks::PRE_SIMULATION
  • Hooks::POST_SIMULATION
  • Hooks::PRE_INIT
  • Hooks::POST_INIT
  • Hooks::PRE_ABORT
  • Hooks::POST_ABORT
  • Hooks::PRE_RESTART
  • Hooks::POST_RESTART

Register to hooks with a block

failures = 0
successes = 0

simulation.notifier.subscribe(Quartz::Hooks::POST_SIMULATION) { successes += 1 }
simulation.notifier.subscribe(Quartz::Hooks::POST_ABORT) { failures += 1 }

Register to hooks with a Notifiable object

class MyNotifiable
  include Quartz::Hooks::Notifiable

  getter successes : Int32 = 0
  getter failures : Int32 = 0

  def notify(hook : Symbol)
    case hook
    when Quartz::Hooks::POST_SIMULATION
      @successes += 1
    when Quartz::Hooks::POST_ABORT
      @failures += 1
    end
  end
end

notifiable = MyNotifiable.new

simulation.notifier.subscribe(Quartz::Hooks::POST_SIMULATION, notifiable)
simulation.notifier.subscribe(Quartz::Hooks::POST_ABORT, notifiable)

Next: Runtime checks

Clone this wiki locally