Timers in Modelica

Our first example demonstrates how to use timers in Modelica. Timers are useful when we want to execute code at some point in the future or repeatedly at some interval.

model Timers
  Real startTime;
  Boolean timer1Fired;
  Boolean timer2Fired;
  Boolean timer2Stopped;

equation
  when time >= startTime + 2 then
    timer1Fired = true;
  end when;

  when time >= startTime + 1 then
    timer2Fired = true;
  end when;

  timer2Stopped = true;

algorithm
  when initial() then
    startTime := time;
    timer1Fired := false;
    timer2Fired := false;
    timer2Stopped := false;
  end when;

  when timer1Fired then
    Modelica.Utilities.Streams.print("Timer 1 fired");
  end when;

  when timer2Stopped then
    Modelica.Utilities.Streams.print("Timer 2 stopped");
  end when;

  when time >= startTime + 2 then
    terminate("Simulation finished");
  end when;
end Timers;

In this Modelica model:

  1. We define two timers using when equations. The first timer fires after 2 seconds, and the second timer would fire after 1 second if not stopped.

  2. We use when statements in the algorithm section to print messages when timers fire or are stopped.

  3. Instead of blocking on a channel, we use Modelica’s event-based system with when clauses to detect when timers fire.

  4. We simulate stopping the second timer by setting timer2Stopped to true immediately.

  5. The simulation runs for 2 seconds before terminating.

To run this model:

  1. Save it in a file named Timers.mo
  2. Use a Modelica-compatible simulation environment (like OpenModelica or Dymola) to compile and simulate the model.
  3. The simulation results should show:
    Timer 2 stopped
    Timer 1 fired

Note that Modelica doesn’t have direct equivalents for goroutines or channels. Instead, it uses a declarative, equation-based approach for modeling dynamic systems and events. The concept of timers is represented using time-based events in the continuous simulation environment that Modelica provides.